How to send and receive messages through a PHP socket in the same program

Dinithi De Silva picture Dinithi De Silva · Feb 25, 2013 · Viewed 9.9k times · Source

I have written a simple socket program to send a message from client to server. That works fine and I need to get a response from the server to client. Can I do it in a same socket program?If yes how can I do it?

Here is my code for the server socket.

<?php
$address="127.0.0.1";
$port="3222";
$sock=socket_create(AF_INET,SOCK_STREAM,0) or die("Cannot create a socket");
socket_bind($sock,$address,$port) or die("Couldnot bind to socket");
socket_listen($sock) or die("Couldnot listen to socket");
$accept=socket_accept($sock) or die("Couldnot accept");
$read=socket_read($accept,1024) or die("Cannot read from socket");
echo $read;

?>

Here is the code for Client socket.

<?php
$address="127.0.0.1";
$port="3222";
$msg="Hello server";

$sock=socket_create(AF_INET,SOCK_STREAM,0) or die("Cannot create a socket");
socket_connect($sock,$address,$port) or die("Could not connect to the socket");
socket_write($sock,$msg);

?>

Can somebody help me please....

Answer

Till Helge picture Till Helge · Feb 25, 2013

You can simply call socket_read() after writing to a socket to wait for an answer.