1

Hello i'm trying to learn and build a socket script in PHP this is my code:

Client:

include_once('server.php');

$host = "localhost"; 
$port    = 1025;

$message = "Hello Server";

// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) { 
 echo "socket_create() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
 }
// connect to server
    socket_bind($socket, $host);
    if (socket_connect($socket, $host, $port) === false) { 
         echo "socket_connect() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
    }
    else { echo "Connected"; }

Server:

// Variables 
$host = "localhost"; 
$port = 1025; 

// No timeout 
set_time_limit(0); 

// Create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Can't create socket..");

if ($socket === false) {
    echo "Unable to create socket. Error: {$errno} : {$errstr}\n"; 
    die();
}


// Bind Socket
if (socket_bind($socket, $host) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
else { echo "Connected to {$host}:{$port}"; }

// Socket listen
if (socket_listen($socket, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}

if (socket_accept($socket) === false) {
    echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}



// Socket close
socket_close($socket);

But i'm missing something that i cant figure out and i dont know what, When im trying to connect from the client it just loads nothing happens, Can anyone here point me in the right direction and tell me what im doing wrong?

4
  • Are you sure that the port 1025 is open ? Commented Nov 11, 2015 at 16:58
  • On the client side it doesn't necessary to bind Commented Nov 11, 2015 at 16:58
  • @RaphaëlVigée don't have a clue :D How do i look this up? Commented Nov 11, 2015 at 17:00
  • Take a look at this : superuser.com/a/622641 Commented Nov 11, 2015 at 17:01

2 Answers 2

4

On your client, you do not want socket_bind(). That is for opening up a connection for other systems to connect to; in short, to become a server.

Our client script:

<?php // client.php
$host = "127.0.0.1"; // connect _does_ do DNS lookups, unlike bind, which is mentioned below, but for simplicity of the example I'm explicitly naming the IP address.
$port    = 1025;
$message = "Hello Server";

// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) {
    // Using die() here because we really don't want to continue on while in an error condition.
    die('socket_create() failed: reason: ' . socket_strerror(socket_last_error($socket));
}

// connect to server
if (socket_connect($socket, $host, $port) === false) { 
     die('socket_connect() failed: reason: ' . socket_strerror(socket_last_error($socket));
}

socket_write($socket, $message);
socket_close($socket);

In your server, you should listen on 0.0.0.0 (or a specific IP address), and not specify a domain name. 0.0.0.0 means to listen to all IP addresses, and any specific IP address means to only listen on the one interface that is configured for that address.

For example, if your server has 2 NICs, one assigned to a public address, say 1.2.3.4, and another assigned to a local address, 192.168.0.2. You also always have your loopback, 127.0.0.1 for free just by having TCP/IP.

If you want to restrict access to your server script to only other hosts on your network, you would set your listen address to 192.169.0.2. Even though your server is accessible through the public IP of 1.2.3.4, this script will simply not listen to any of that traffic.

If you want to restrict access to your server script to only other processes running on that machine, you need to use 127.0.0.1. Using "localhost" will not keep anyone out, because bind does not perform any DNS lookups (and PHP's socket_bind() is only a thin wrapper around the BSD Sockets based system call to bind). It doesn't even look at the hosts file. Thus, any non-IP string will be cast to an integer, usually resulting in it becoming 0, and that 0 will be converted to 0.0.0.0, which will allow access from all interfaces, despite you thinking that you're only listening to localhost traffic.

When you accept a connection, it creates a new socket resource, which I've named $clientSocket in the example below. Don't get confused between the sockets created when a new host connects and your listening socket; they're very similar, but with a very important distinction: When your listening socket has a new message, it is always saying that there is a new host connecting, so you should accept. If it is a client socket, then you'll be using read or recv. (I prefer recv because of the finer control, but I use read in the example below to more clearly show the process rather than adding confusion by having references... which is also why I'm not going to show select.)

Our server script:

<?php //server.php
$listen_address = "0.0.0.0";
$port = 1025; 
$maxBuffer = 1024; // bytes, not characters.

// No timeout 
//set_time_limit(0); // Shouldn't be necessary in CLI.

// Create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if ($socket === false) {
    die('Unable to create socket: ' . $socket_strerror(socket_last_error($socket)) . PHP_EOL);
}

// Bind Socket
if (socket_bind($socket, $listen_address, $port) === false) {
    die('socket_bind() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
}
else { 
    echo "Connected to {$listen_address}:{$port}\n"; 
}

// Accept our client connection

// Typically, this would be where we'd put a loop with socket_select,
// but for our example, since we'll be exiting as soon as we have our
// first packet, we'll listen, accept, read, then close.
if (socket_listen($socket) === false) {
    die('socket_listen() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
}

$clientSocket = socket_accept($socket);
if ($clientSocket === false) {
    die('socket_accept() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
}

// Because the contents of a packet could be longer than our
// buffer size, it's advisable to peek at the socket to see
// if it would block before saying that our message is complete.
// In our example, we're receiving 12 bytes out of our maximum 1024,
// so I leave handling large packets as an exercise for the developer.
$message = socket_read($clientSocket, $maxBuffer);

var_dump($message);

// Socket close
socket_close($clientSocket);
socket_close($socket);

And finally, here's how to run the mess above.

Note that I'm going to have both the server and client run in the same TTY, I'll have the server run as a background process (use the & modifier), but I will not be redirecting their output, so both scripts will be spitting their output into the same terminal.

myhost.mydomain$ php ./server.php &
[8] 76399
Connected to 0.0.0.0:1025
myhost.mydomain$ php ./client.php
string(12) "Hello Server"
[8]+  Done                    php ./server.php
Sign up to request clarification or add additional context in comments.

5 Comments

omg that was a really good explanation. I used your script you showed to me just to test if i get it to work! And yes it did work only thing is that i get a new error "Normally only one user is allowed per socketadress"
@Tommy That error could be from previous attempts to connect on that port from a process that hasn't closed fully. Try using a different port, perhaps something around 6000.
I get the same error with another port aswell tested 3000, 4000, 5000, 6000, 7000 and got the same error
Unfortunately, I'm not much of a Windows sockets dev. This might be a good candidate for another question... a quick Google search doesn't show anything helpful for PHP, only for .NET code.
I've noticed that aswell! But i mark your answer as the right answer and thank you very much for the help! :)
1

Your implementation of the server is wrong. Your server should have a loop which is always active listening to connections.

Server

# Create Socket
$socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
# Bind a host and a port to the socket
socket_bind($socket, $host, $port);
# Listen for connection in the socket you just created
socket_listen($socket);

# This is the heart of the server, without it, it can not serve.
while(true)
{
    # Accept Client connection if client socket connects
    $client = socket_accept($socket);

    # Logic @todo Reponse to client
    print "Connected." // For testing purposes, see if client actually connected

    # Close client connection
    socket_close($client);
}

To connect from your client to the server use socket_connect, documentation here.

2 Comments

That solved a lot of things :) But when i try to bind port aswell i get error that i have invalid arguments? :S
paste.ofcode.org/CHNcpG2ywnPeXh6P3uWpuT - I posted it there, can i have something with the port thing to do? I still dont know what port or anything i should use :S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.