Socket programming in PHP

Sockets let client and server processes communicate. This introduction builds a PHP server that receives a string and returns it reversed.

Socket programming in PHP

Introduction

Sockets enable communication between processes, often in a client-server model. A client and a server need a connection to exchange data; socket programming establishes that connection.

php socket schema

Code example

Build a server that receives a text message from a client and returns the same message in reverse.

SERVER PHP

1. Set the host and port variables.

$host = "127.0.0.1";
$port = 5353;
// No Timeout 
set_time_limit(0);

2. Create the socket.

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");

3. Bind the socket to the host and port. The socket is associated with the chosen IP address and port number.

$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");

4. Listen for incoming connections. After binding, the server waits for a client.

$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

5. Accept an incoming connection. The accepted connection produces a second socket, stored in $spawn, for communication with that client.

$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");

6. Read the message from the client socket.

$input = socket_read($spawn, 1024) or die("Could not read input\n");

7. Reverse the message.

$output = strrev($input) . "\n";

8. Send the response to the client socket.

socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");

Close the sockets.

socket_close($spawn);
socket_close($socket);

Share

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0