Php and tcp/ip sockets
This is a quick guide to learning socket programming in php. Socket programming php is very similar to C. Most functions are similar in names, parameters and output.
However unlike C, socket programs written in php would run the same way on any os that has php installed. So the code does not need any platform specific changes (mostly).
To summarise the basics, sockets are the fundamental "things" behind any kind of network communications done by your computer.
For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype. Any network communication goes through a socket.
Before you begin
This tutorial assumes that you already know php and also how to run php scripts from the command-line/terminal.
Php scripts are normally run from inside the browser by placing them in the apache root directory like /var/www. However these command-line programs can be run from any directory. They can be run from browsers as well.
So lets begin with sockets.
1. Creating a socket
This first thing to do is create a socket. The socket_create
function does this.
Here is a code sample :
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
Function socket_create
creates a socket and returns a socket descriptor which can be used in other network commands.
The above code will create a socket with the following properties ...
Address Family : AF_INET (this is IP version 4)
Type : SOCK_STREAM (this means connection oriented TCP protocol)
Protocol : 0 [ or IPPROTO_IP This is IP protocol]
Error handling
If any of the socket functions fail then the error information can be retrieved using the socket_last_error and socket_strerror functions.
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created";
Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server using this socket. We can connect to www.google.com
Note
Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.
2. Connect to a Server
We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to. So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample. A little later on we shall see how to find out the ip address of a given domain name.
The last thing needed is the connect
function. It needs a socket and a sockaddr structure to connect to. Here is a code sample.
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; if(!socket_connect($sock , '74.125.235.20' , 80)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not connect: [$errorcode] $errormsg \n"); } echo "Connection established \n";
Run the program
$ php /var/www/socket.php Socket created Connection established
It creates a socket and then connects. Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection. This logic can be used to build a port scanner.
OK, so we are now connected. Lets do the next thing , sending some data to the remote server.
Quick Note
The concept of "connections" apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable "stream" of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by other data.
Other sockets like UDP , ICMP , ARP dont have a concept of "connection". These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.
3. Sending Data
Function send
will simply send data. It needs the socket descriptor , the data to send and its size.
Here is a very simple example of sending some data to google.com ip :
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; //Connect socket to remote server if(!socket_connect($sock , '74.125.235.20' , 80)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not connect: [$errorcode] $errormsg \n"); } echo "Connection established \n"; $message = "GET / HTTP/1.1\r\n\r\n"; //Send the message to the server if( ! socket_send ( $sock , $message , strlen($message) , 0)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not send data: [$errorcode] $errormsg \n"); } echo "Message send successfully \n";
In the above example , we first connect to an ip address and then send the string message "GET / HTTP/1.1\r\n\r\n" to it.
The message is actually a http command to fetch the mainpage of a website.
Now that we have send some data , its time to receive a reply from the server. So lets do it.
Note
When sending data to a socket you are basically writing data to that socket. This is similar to writing data to a file. Hence you can also use the write
function to send data to a socket. Later in this tutorial we shall use write function to send data.
4. Receiving Data
Function recv
is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.
<?php if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; //Connect socket to remote server if(!socket_connect($sock , '74.125.235.20' , 80)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not connect: [$errorcode] $errormsg \n"); } echo "Connection established \n"; $message = "GET / HTTP/1.1\r\n\r\n"; //Send the message to the server if( ! socket_send ( $sock , $message , strlen($message) , 0)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not send data: [$errorcode] $errormsg \n"); } echo "Message send successfully \n"; //Now receive reply from server if(socket_recv ( $sock , $buf , 2045 , MSG_WAITALL ) === FALSE) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not receive data: [$errorcode] $errormsg \n"); } //print the received message echo $buf;
Here is the output of the above code :
$ php /var/www/socket.php Socket created Connection established Message send successfully HTTP/1.1 302 Found Location: http://www.google.co.in/ Cache-Control: private Content-Type: text/html; charset=UTF-8 Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com Set-Cookie: PREF=ID=3c2e53ffcc387bbb:FF=0:TM=1342766363:LM=1342766364:S=DTuSOuahFqyd6vjp; expires=Sun, 20-Jul-2014 06:39:24 GMT; path=/; domain=.google.com Set-Cookie: NID=62=HZWk5tBSunVEofFri475wbeCNiChGf_bs7Pz_Z32hfm-B-0M4JRhz-pptjtChOk6lVepLBhOtB2pNHCT5DynobfZaGQaPS5Dh9Rq4YAqt40hExsePHEyA0ECMKjq5KeE; expires=Sat, 19-Jan-2013 06:39:24 GMT; path=/; domain=.google.com; HttpOnly P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info." Date: Fri, 20 Jul 2012 06:39:24 GMT Server: gws Content-Length: 221 X-XSS-Protection: 1; mode=block X-Frame-Options: SAMEORIGIN <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>302 Moved</TITLE></HEAD><BODY> <H1>302 Moved</H1> The document has moved <A HREF="http://www.google.co.in/">here</A>. </BODY>
We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com replied with the content of the page we requested. Quite simple!
Now that we have received our reply, its time to close the socket.
5. Close socket
Function socket_close
is used to close the socket.
socket_close($sock);
Thats it.
Lets Revise
So in the above example we learned how to :
1. Create a socket
2. Connect to remote server
3. Send some data
4. Receive a reply
Its useful to know that your web browser also does the same thing when you open www.google.com
This kind of socket activity represents a CLIENT. A client is a system that connects to a remote system to fetch data.
The other kind of socket activity is called a SERVER. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.
Now its time to do some server tasks using sockets. But before we move ahead there are a few side topics that should be covered just incase you need them.
Get IP address of a hostname/domain
When connecting to a remote host , it is necessary to have its IP address. Function gethostbyname
is used for this purpose. It takes the domain name as the parameter and returns the ip address.
Quick example
$ip_address = gethostbyname("www.google.com"); // = 173.194.75.104
So the above code can be used to find the ip address of any domain name. Then the ip address can be used to make a connection using a socket.
Server Programming
OK now onto server things. Servers basically do the following :
1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send
We have already learnt how to open a socket. So the next thing would be to bind it.
1. Bind a socket
Function bind
can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.
Quick example
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; // Bind the source address if( !socket_bind($sock, "127.0.0.1" , 5000) ) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [$errorcode] $errormsg \n"); } echo "Socket bind OK \n";
Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.
This makes it obvious that you cannot have 2 sockets bound to the same port. There are exceptions to this rule but we shall look into that in some other article.
2. Listen for connections
After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function socket_listen
is used to put the socket in listening mode. Just add the following line after bind.
//listen socket_listen ($sock , 10)
The second parameter of the function socket_listen is called backlog. It controls the number of incoming connections that are kept "waiting" if the program is already busy. So by specifying 10, it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected. This will be more clear after checking socket_accept.
Now comes the main part of accepting new connections.
3. Accept connection
Function socket_accept
is used for this.
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; // Bind the source address if( !socket_bind($sock, "127.0.0.1" , 5000) ) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [$errorcode] $errormsg \n"); } echo "Socket bind OK \n"; if(!socket_listen ($sock , 10)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not listen on socket : [$errorcode] $errormsg \n"); } echo "Socket listen OK \n"; echo "Waiting for incoming connections... \n"; //Accept incoming connection - This is a blocking call $client = socket_accept($sock); //display information about the client who is connected if(socket_getpeername($client , $address , $port)) { echo "Client $address : $port is now connected to us."; } socket_close($client); socket_close($sock);
Output
Run the program. It should show
$ php /var/www/server.php Socket created Socket bind OK Socket listen OK Waiting for incoming connections...
So now this program is waiting for incoming connections on port 5000. Dont close this program , keep it running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type
$ telnet localhost 5000
It will immediately show the following output:
$ telnet localhost 5000 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Connection closed by foreign host.
And the server output will show
Client 127.0.0.1 : 36689 is now connected to us.
So we can see that the client connected to the server. Try the above steps till you get it working perfect.
Note
The socket_getpeername function is used to get details about the client which is connected to the server via a particular socket.
We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.
Sending message back to client
Function socket_write
can be used to write something to the socket of the incoming connection and the client should see it. Here is an example :
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; // Bind the source address if( !socket_bind($sock, "127.0.0.1" , 5000) ) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [$errorcode] $errormsg \n"); } echo "Socket bind OK \n"; if(!socket_listen ($sock , 10)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not listen on socket : [$errorcode] $errormsg \n"); } echo "Socket listen OK \n"; echo "Waiting for incoming connections... \n"; //Accept incoming connection - This is a blocking call $client = socket_accept($sock); //display information about the client who is connected if(socket_getpeername($client , $address , $port)) { echo "Client $address : $port is now connected to us. \n"; } //read data from the incoming socket $input = socket_read($client, 1024000); $response = "OK .. $input"; // Display output back to client socket_write($client, $response); socket_close($client);
Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :
$ telnet localhost 5000 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. happy OK .. happy Connection closed by foreign host.
So the client(telnet) received a reply from server.
We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.
It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept
in a loop so that it can receive incoming connections all the time.
4. Live Server
So a live server will be alive always. Lets code this up
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; // Bind the source address if( !socket_bind($sock, "127.0.0.1" , 5000) ) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [$errorcode] $errormsg \n"); } echo "Socket bind OK \n"; if(!socket_listen ($sock , 10)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not listen on socket : [$errorcode] $errormsg \n"); } echo "Socket listen OK \n"; echo "Waiting for incoming connections... \n"; //start loop to listen for incoming connections while (true) { //Accept incoming connection - This is a blocking call $client = socket_accept($sock); //display information about the client who is connected if(socket_getpeername($client , $address , $port)) { echo "Client $address : $port is now connected to us. \n"; } //read data from the incoming socket $input = socket_read($client, 1024000); $response = "OK .. $input"; // Display output back to client socket_write($client, $response); }
We havent done a lot there. Just put the socket_accept in a loop.
Now run the server program in 1 terminal , and open 3 other terminals.
From each of the 3 terminal do a telnet to the server port.
Each of the telnet terminal would show :
$ telnet localhost 5000 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. happy OK .. happy Connection closed by foreign host.
And the server terminal would show
$ php /var/www/server.php Socket created Socket bind OK Socket listen OK Waiting for incoming connections... Client 127.0.0.1 : 37119 is now connected to us. Client 127.0.0.1 : 37122 is now connected to us. Client 127.0.0.1 : 37123 is now connected to us.
So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program. All telnet terminals would show "Connection closed by foreign host."
Good so far. But still there is not effective communication between the server and the client. The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections , and handle multiple connections together.
5. Handling Connections
To handle every connection we need a separate handling code to run along with the main server accepting connections. One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.
However php does not support threading directly.
Another method is to use the select function. The select function basically 'polls' or observers a set of sockets for certain events like if its readable, or writable or had a problem or not etc.
So the select function can be used to monitor multiple clients and check which client has send a message.
Quick Example:
error_reporting(~E_NOTICE); set_time_limit (0); $address = "0.0.0.0"; $port = 5000; $max_clients = 10; if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [$errorcode] $errormsg \n"); } echo "Socket created \n"; // Bind the source address if( !socket_bind($sock, $address , 5000) ) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [$errorcode] $errormsg \n"); } echo "Socket bind OK \n"; if(!socket_listen ($sock , 10)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not listen on socket : [$errorcode] $errormsg \n"); } echo "Socket listen OK \n"; echo "Waiting for incoming connections... \n"; //array of client sockets $client_socks = array(); //array of sockets to read $read = array(); //start loop to listen for incoming connections and process existing connections while (true) { //prepare array of readable client sockets $read = array(); //first socket is the master socket $read[0] = $sock; //now add the existing client sockets for ($i = 0; $i < $max_clients; $i++) { if($client_socks[$i] != null) { $read[$i+1] = $client_socks[$i]; } } //now call select - blocking call if(socket_select($read , $write , $except , null) === false) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not listen on socket : [$errorcode] $errormsg \n"); } //if ready contains the master socket, then a new connection has come in if (in_array($sock, $read)) { for ($i = 0; $i < $max_clients; $i++) { if ($client_socks[$i] == null) { $client_socks[$i] = socket_accept($sock); //display information about the client who is connected if(socket_getpeername($client_socks[$i], $address, $port)) { echo "Client $address : $port is now connected to us. \n"; } //Send Welcome message to client $message = "Welcome to php socket server version 1.0 \n"; $message .= "Enter a message and press enter, and i shall reply back \n"; socket_write($client_socks[$i] , $message); break; } } } //check each client if they send any data for ($i = 0; $i < $max_clients; $i++) { if (in_array($client_socks[$i] , $read)) { $input = socket_read($client_socks[$i] , 1024); if ($input == null) { //zero length string meaning disconnected, remove and close the socket unset($client_socks[$i]); socket_close($client_socks[$i]); } $n = trim($input); $output = "OK ... $input"; echo "Sending output to client \n"; //send response to client socket_write($client_socks[$i] , $output); } } }
Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.
The telnet terminals would show :
$ telnet localhost 5000 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. Welcome to php socket server version 1.0 Enter a message and press enter, and i shall reply back hello OK ... hello how are you OK ... how are you
The server terminal might look like this
$ php /var/www/server.php Socket created Socket bind OK Socket listen OK Waiting for incoming connections... Client 127.0.0.1 : 36259 is now connected to us. Sending output to client Sending output to client Client 127.0.0.1 : 36274 is now connected to us. Sending output to client Sending output to client Client 127.0.0.1 : 36276 is now connected to us. Sending output to client Sending output to client
The above connection handler takes some input from the client and replies back with the same. Simple! Here is how the telnet output might look
So now we have a server thats communicative. Thats useful now.
Conclusion
By now you must have learned the basics of socket programming in php. You can try out some experiments like writing a chat client or something similar.
If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.
Cool, really really helpful for a beginner in PHP!
Thank you, very good tutorial ;)
I really appreciate your work. If possible, can you make Youtube video on this tutorial. Doing so will further makes clear understanding.
Please notify if that happens.
Thank you once again.
Awsome tutorial.
Excellent thanks for given time and sharing your knowledge
Thanks for the code, works perfect, but i have one problem, we send Decimal numbers, but with this code only can receive ascii data, and i want to send and receive Decimal data, if I send a “68” i receive a “D”
Can somebody help me to fix it?
Thanks!!
I didn’t connect with telnet but with the client script from the start of the tutorial, changed it so it uses port 5000 and localhost. Only It keeps waiting for a response from the server. If I change the buffersize to a very small number it will echo the response, but only the amount of characters that where read ofcourse. Should I end the response from the server with some sort of escape signal?
I tried ^] but that didn’t work.
Wonderfull Tutorial… Thanks alot
Worked great
it is nice code. Can i has additional for this code.
if no data send to server at 10 sec , close the socket.
how to do this?
awesome tutorial …
clean explanation….
Thank you so much for sharing this…
How come every socket example on the web uses localhost for getting clients, how should this example be modified to for example let someone “telnet 90.32.123.34 12345” to my socket which is bind to address of 90.32.123.31 and port 12345??? Do I have to modify the firewall on my server or what??
I need one favour from ur side …. I am working on a project where I dont know the ip add of the client
Like 1 device will be localhost the other device ip i dont know how can I get the ip address of other device
Man you did great job, please tell me what is the best way to thank you…
I am using a script which is used for receiving data from telnet or hardware but there is no error and i am unable to connect with it and it is working properly on my localhost but not working on server please help me in it And Thank you
Hi,
How do i get the client (device) MAC and IP address??
Basic but great stuff :)
I do but. the problem that i’m facing is i didn’t work with CLI and unable to run the server. How can i test it in browser or provide me step by step php on CLI tutorial.
Thanks.
Hi, you need to go into a folder where PHP is installed or if you are already defined the path then you are good to go with Command Prompt.
How To run server.php:
c:/path/php/>
“php c:/path/server.php” This one is your command for server
How to connect the client: “telnet localhost 5000” this one is your command for client
Great tutorial. Thanks!
I am trying to understand the last example of handling connection but I ca’t, so please could you explain how it works.
I am able to communicate with multiple clients, but i am not able to send data of different clients on same time. Is it possible with this code or not?
Also, one more thing: line 112 isn’t used anywhere, so it can be removed:
$n = trim($input);
yeah, but this one can be used to check the input command from client like
if($n == “exit”) …. then close the session etc …
Excellent tutorial :)
As mentioned already, there’s a bug in your code, lines 108-109:
unset($client_socks[$i]);
socket_close($client_socks[$i]);
When you unset $client_socks[$i], you can no longer call socket_close on it. Thus, these two lines should be swapped:
socket_close($client_socks[$i]);
unset($client_socks[$i]);
can i make a communication between a java socket and a php socket !! thanks
Great tutorial and I understand finally a socket issue. Thank you.
its help me a lot ..i m making a website which will connect the world ..so i need a real time notification and a live chat..so my questions is “with php can i implement this or i should do more?” it will have millions of users
..
This is a great tutorial! But I have an issue, when I added the while loop, and send anything through telnet, I don’t get a response, it keeps waiting for things to be written on telnet end. Any help will be appreciated.
It’s works well, but the enter event not working this is my out put and there is also warrnings see bellow:
Setting environment for using XAMPP for Windows.
manee.osman@DEV8 c:xampp
# echo ‘Hello’;
‘Hello’;
manee.osman@DEV8 c:xampp
# php C:xampphtdocs”JAVASCRIPT PHP TESTS”socket.example.php
Could not open input file: C:xampphtdocs”JAVASCRIPT
manee.osman@DEV8 c:xampp
# php C:xampphtdocsJAVASCRIPT_PHP_TESTSsocket.example.php
Socket created
Socket bind OK
Socket listen OK
Waiting for incoming connections…
Client 127.0.0.1 : 37717 is now connected to us.
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Client 127.0.0.1 : 37735 is now connected to us.
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Sending output to client
Warning: socket_close() expects parameter 1 to be resource, null given in C:xampphtdocsJAVASCRIPT_PHP_TESTSsocket.example.php on line 110
Sending output to client
Warning: socket_write() expects parameter 1 to be resource, null given in C:xampphtdocsJAVASCRIPT_PHP_TESTSsocket.example.php on line 120
Warning: socket_close() expects parameter 1 to be resource, null given in C:xampphtdocsJAVASCRIPT_PHP_TESTSsocket.example.php on line 110
Sending output to client
Warning: socket_write() expects parameter 1 to be resource, null given in C:xampphtdocsJAVASCRIPT_PHP_TESTSsocket.example.php on line 120
hi,
i am getting an error.
Warning: socket_recv() [function.socket-recv]: unable to read from socket [0]: The operation completed successfully.
in C:xampphtdocssocketclient_receive_msg.php on line 38
Could not receive data: [0] The operation completed successfully.
Please Help.
Thanks in advance.
thx!
Your explanation it’s clear as water, thank you so much, you have showed me the path to the solution I need.
again, thank you very, very much.
Thanks for the fantastic socket tutorial on windows terminal….Just one thing i didn’t understand…when I tried to run it on browser….Nothing is happened…So how could I use it for the chat server??
if you run the server in a browser, the page shall keep loading since it is a never ending script.
then you can connect to it from console using the telnet command.
Thanks for reply!!
Actually I want this script to use for developing a chat application that will run on the browser, and will be used just like done in facebook chating…How can I do it??
I used a big class PHPWebSocket.php found from googling but, it is too long and tough to understand…
This post shows the usage of tcp/ip sockets. these are different from websockets.
tcp/ip sockets are not related to browsers.
to develop a chat like application use ajax. check out some tutorials on the subject.
hi,
i am getting an error.
Warning: socket_recv() [function.socket-recv]: unable to read from socket [0]: The operation completed successfully.
in C:xampphtdocssocketclient_receive_msg.php on line 38
Could not receive data: [0] The operation completed successfully.
Please Help.
Thanks in advance.
Solved it …The IP mentioned is different from the current Google IP.
Thanks for your extensive tutorial Silver Moon. Most of it works for me but I have the problem that when I press a key in my client console it straight goes to the server. So I can only send single characters. According to your tutorial this is not expected behavior?
BTW, I do get an error when disconnecting, but I found it is due to unsetting a client resource in the clients array. Using array_splice solved this issue.
what socket client are you using ? telnet ?
with telnet the message should not go to server unless the enter key is pressed.
Maybe it has to do with the Windows environment? But I tried bot windows console telnet and telnet in Putty. They give the same problem.
yes, on windows the telnet command is in character mode and due to that every key stroke is transmitted right away to the server.
this can be fixed by either of the following 2 steps :
1. setting the telnet into line mode
2. modifying the server code to reply only when it receives a newline.
3. put putty in passive negotiation mode and it will send only on pressing enter key.
or use netcat, ncat (from nmap package). it too has same syntax as telnet.
C:> ncat localhost 5000
Line mode didn’t do what I expected, but passive mode in putty did the trick. Tnx!
how can I change telnet input mode into line mode?
How to change putty to passive mode? All working except this!
how to set telnet into line mode?
Here is the simple server side solution, just need to change this line and telnet will send the command after pressing enter.
Line Number 103
$input = socket_read($client_socks[$i], 1024)
with
$input = socket_read($client_socks[$i], 1024, PHP_NORMAL_READ);
if (!$input = trim($input)) continue;
Hai,
There are two questions.
Question 1:
I used the gethostbyname function to get the ip address of google and found the ip address of google as 173.194.38.176.Then i typed the code given under the sub heading “sending data” and in that i replaced the line
if(!socket_connect($sock , ‘74.125.235.20’ , 80))with if(!socket_connect($sock , ‘173.194.38.176’ , 80)).It outputs “Socket created
Connection established
Message send successfully”.But it is not displaying the google web page why?
Question 2:
Similarly i typed the code in receive data but used the ip address as 173.194.38.176 instead of 74.125.235.20 the ip address of google.It outputs every thing from socket created to
X-Frame-Options: SAMEORIGIN.But it doesnot display the HTML code.Instead it displays”302 moved.the document has been moved”.why?
Question 1 :
You have to use the code under “Receiving Data”. It will receive the google web page and display it. The “Sending data” code only sends the http requests and quits.
Question 2 :
The “302 moved” message is the output google has send. It means that another http request has to be made to fetch the actual page. Its related to http protocol.
The socket program is working fine.
hai,
for me the second program shows an error.the error is”Call to undefined function socket_create() in C:wampwwwhaisocket_creation.php on line 2″.what shall i do now?
you need to enable the socket extension in wamp. Click the wamp icon in the taskbar, go to
PHP => PHP extensions and click php_sockets. Make sure it has a tick mark to indicate that it is enabled.
After that restart apache. Now socket functions should work fine.
thanks it worked
hai,
for me the there is an error in executing the second program.the error is
“Call to undefined function socket_create() in C:wampwwwhaisocket_creation.php on line 2”.what shall i do now?
so far i have found it perfect!! Thanks :) but i am having issues.. the code works perfect for me on localhost but on my remote server it says “Socket created Could not bind socket : [98] Address already in use” how do i proceed :)
Change the socket number you’re attempting to bind. 98 is pretty low, and likely used for something. Pick something high and random.
98 is the error code, not the port number.
Thnks, very nice info.
This is the first Googled socket server that I have found that is robust after trying half a dozen others.
Unlike other fails that I have tried, this one doesn’t quit the entire socket server when one telnet session disconnects with “^]” followed by “close”. It is a fantastic starting point and well explained…
Don’t waste your time elsewhere. Use this. It rocks!
Awesome, Cheers!
I have only one question
I tried to send received messages to all clients at the same time, but I have not achieved :(
Try something like this from line 118 does not work:
for ($i = 0; $i < $max_clients; $i++){
socket_write($client_socks[$i] , $output);
}
Is there any solution?
can be used to create a http server in php :)
Warning: socket_bind() [function.socket-bind]: unable to bind address [0]: Only one usage of each socket address (protocol/network address/port) is normally permitted. in C:\xampp\htdocs\First programm\index.php on line 16
Could not bind socket : [10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.
please help me i am using this in Windows
change the port number you are binding the socket to.
very nice
very nice
So much great that I have even not seen anything like this in any PHP book.
A serious well done on this article. I used it as a side note whilst researching PHP sockets in detail.
Cheers!
perfect, this tut is what i was looking for. thank you so much <3
Very nice tutorial…saved my lot of time thanks buddy
Very neat info …
Excellent !! I want to know some more idea about socket programming for web service.
Excellent tutorial !!