Click here to Skip to main content
Click here to Skip to main content

Socket Programming in PHP

By , 18 Jul 2012
 

Introduction

Sockets are used for interprocess communication. Interprocess communication is generally based on client-server model. In this case, client-server are the applications that interact with each other. Interaction between client and server requires a connection. Socket programming is responsible for establishing that connection between applications to interact.

By the end of this tip, we will learn how to create a simple client-server in PHP. We will also learn how client application sends message to server and receives it from the same.

Using the Code

Aim: Develop a client to send a string message to server and server to return reverse of the same message to client.

PHP SERVER

Step 1: Set variables such as "host" and "port"

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

Port number can be any positive integer between 1024 -65535.

Step 2: Create Socket

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

Step 3: Bind the socket to port and host

Here the created socket resource is bound to IP address and port number.

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

Step 4: Start listening to the socket

After getting bound with IP and port server waits for the client to connect. Till then it keeps on waiting.

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

Step 5: Accept incoming connection

This function accepts incoming connection request on the created socket. After accepting the connection from client socket, this function returns another socket resource that is actually responsible for communication with the corresponding client socket. Here “$spawn” is that socket resource which is responsible for communication with client socket.

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

So far, we have prepared our server socket but the script doesn't actually do anything. Keeping to our aforesaid aim, we will read message from client socket and then send back reverse of the received message to the client socket again.

Step 6: Read the message from the Client socket

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

Step 7: Reverse the message

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

Step 8: Send message to the client socket

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

Close the socket

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

This completes with the server. Now we will learn to create PHP client.

PHP CLIENT

The first two steps are the same as in the server.

Step 1: Set variables such as "host" and "port"

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

Note: Here the port and host should be same as defined in server.

Step 2: Create Socket

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

Step 3: Connect to the server

$result = socket_connect($socket, $host, $port) or die("Could not connect toserver\n");

Here unlike server, client socket is not bound with port and host. Instead it connects to server socket, waiting to accept the connection from client socket. Connection of client socket to server socket is established in this step.

Step 4: Write to server socket

socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");

In this step, client socket data is sent to the server socket.

Step 5: Read the response from the server

$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;

Step 6: Close the socket

socket_close($socket);

Complete Code

SERVER (server.php)

// set some variables
$host = "127.0.0.1";
$port = 25003;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : ".$input;
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);

CLIENT (client.php)

$host    = "127.0.0.1";
$port    = 25003;
$message = "Hello Server";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket);

After creating the above files (server.php and client.php), do as follows:

  1. Copy these files in www directory (in case of WAMP), located at C:\wamp.
  2. Open your web browser and type localhost in the address bar.
  3. Browse server.php first followed by client.php.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ankur.Saxena17
Web Developer CDAC Hyderabad
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionhi problemmembermridul samadder12 Mar '13 - 13:24 
can i make chat app by that??
 
when i run http://localhost/phpchat/server.php it keeps loading but then when i load http://localhost/phpchat/client.php i see some messages then i reload client.php and got that error -
Message To server :Hello Server
( ! ) Warning: socket_connect() [function.socket-connect]: unable to connect [0]: No connection could be made because the target machine actively refused it. in C:\xampp\htdocs\phpchat\client.php on line 11
 
tell me how can i solve and make php chat app like fb i think so.
AnswerRe: hi problemmemberankur170112 Mar '13 - 18:47 
Hello Mridul,
Once you load Server socket it goes in waiting state - LISTENING the client socket, this is a sought of blocking function which means that the server code is not executed further till a client socket connects).
 
Then u load the client socket, now here
-> Client socket connects to Server Socket.
-> Message exchange takes place.
-> Then Server sockets stops listening as per the code.
Now when u again load the client then there is no SERVER socket listening to it..
So that is why u are facing such an Warning.
 
To develop a chat application
-> Your server must be in listening state always and there should a proper sync between server n client so that they may continuously exchange messages...
GeneralRe: hi problemmembermridul samadder13 Mar '13 - 1:47 
so how do i make server always running? any tutorial on that for making chat if possible via socket.let's discuss about chat app
GeneralMy vote of 5memberconfidential9920 Jul '12 - 3:19 
Excellent article! I hope you will write a series of articles on PHP sockets. Well written and easy to follow articles on this topic are hard to find.
Questionhelp mememberdesatir731612 Jul '12 - 9:21 
Hi ankur
Ur article was so helpful for me because i want to create server/client chat service,
So would u plz say me where i can ask all my question about this topic or get more info about this?
I need this for my project
Thanks
AnswerRe: help mememberankur170115 Jul '12 - 18:23 
Hello Sir,
It seems that you must change your php.ini file settings to uncomment
"extension=php_sockets.dll".
To do so :
Step 1) Remove';'(semi-colon) that you will see before "extension=php_sockets.dll" line in php.ini file.
Step 2) Re-Start your wamp server.
 
Then try the code i hope this will solve your problem.
QuestionServer Step 8memberW6WXY10 Jul '12 - 8:15 
Server Step 8 should be
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
GeneralRe: Server Step 8memberankur170115 Jul '12 - 18:16 
Yes you are perfectly right.... I sincerely apologize for the mistake...I have made the due changes in the post.... Thank You dear...

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 18 Jul 2012
Article Copyright 2012 by Ankur.Saxena17
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid