0

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....

Dinithi De Silva
  • 1,142
  • 5
  • 28
  • 46

2 Answers2

2

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

Till Helge
  • 9,253
  • 2
  • 40
  • 56
  • But I need to create a user interface to send and receive messages through input textboxes.Is there any possible way to do it? I have tried it, but the client waits for the user input from the server and fails to run the program. – Dinithi De Silva Feb 25 '13 at 13:43
  • 1
    You will need AJAX to achieve this. Have a look at some PHPChat software...there are quite a few of them out there. Will take way to long to explain all the details here. – Till Helge Feb 25 '13 at 14:02
0

Here is a very good example which works for me

Ali
  • 387
  • 1
  • 7
  • 25