Introduction to Socket Programming with PHP
Pages: 1, 2
Sockets programming in PHP
In the game, the small men were actually network sockets, and the controls represented my favorite programming language -- PHP!
The network sockets support in PHP doesn't include the most advanced features (yet) like the C implementation does, but it's probably enough for 95 percent of all network applications, and that's not bad at all. Also, you'll be able to write real network applications using such an easy-to-use language as PHP. Let's look at a simple TCP server. See listing 1 here.
Actually, the similarities between this program, and the made-up game we looked at earlier are quite clear. Let's discuss this for a moment. First, on line 8, we use set_time_limit(0) to tell PHP that we want to be able to wait for connections for an unlimited amount of time. This is the same as telling the men to wait by the hatch forever (or at least until we explicitly tell them to go away from there).
On lines 11 through 15, we create a new socket. This is known as the global socket and will be the one that checks for incoming connections. (In the analogy, this socket is represented by the man in control of the hatch in Computer I.) For this, we use the socket() function, which takes a total of three arguments. However, I won't try to explain these parameters, and then call this article an introduction to network programming. By the time you need to specify any other arguments than the ones we use here, you'll be quite into network programming already. However, one thing that can be good to know is that the second argument, SOCK_STREAM declares that we want to use the
TCP protocol (in contrast to UDP).
On lines 18 through 22, the newly created socket is bound to an IP address and a port. Since we're going to run this program on our local machine only, we use 127.0.0.1 as the IP address. The port we use, 10000, is picked at random. You can actually use any port between 1024 and the 65535 that isn't already in use. To draw a parallel to the analogy -- this is the same as telling one of the small men which network connection (hatch) to control, and what specific network data he is responsible for. If a packet arrives, which claims to be destined for port 10000, our small man knows that he is the one to take care of it (Yes, this may sound weird, but the small men actually can speak to the data packets!).
With the introduction of ports, you've probably already understood that there can be many men waiting for something to arrive at the same hatch. The port where the data is sent decides if one particular man should take care of the incoming data or not. So, our man will only care about the data that's going to port 10000.
Until now, we've just informed the man of what he should do, but we haven't really sent him instructions yet. This is done on lines 28 through 31 where we tell the man move from his sofa and get to the hatch. On lines 34 through 38, we also tell him stay there and open the hatch if it's needed. In programming terms, the accept_connect() function will wait until a connection arrives. So, the program will stop executing here until we use telnet on it a little later. Also note that when a connection is detected, accept_connect() will create another socket, called $msgsock, which will handle the communication with the connecting side. This is the third man that showed up in Figure 4 (he took care of the incoming data).
On lines 41 through 46, we send the visitor our welcome message using the write() function. Note that this is done by $msgsock because $sock is busy with his hatch, remember? At this stage, the accept_connect() function has already detected a connection, and therefore the execution of the script has reached this far. Or, in the analogy, the man saw something coming, opened the hatch, and asked the packet where it was going. The packet answered "port 10000", so he let it in and passed it to his helper, $msgsock.
On lines 49 through 54, something quite interesting happens. Here, we tell the second man, $msgsock, to go and wait at the hatch as well. This is to make sure he is ready when $sock lets in something he needs to take care of. In programming terms, we use read() to read data from our connection. However, for us to be able to receive any data, it first has to be sent from the other end. Like accept_connect(), the read() command will wait until something happens. When data has arrived for port 10000, the second man, $msgsock, will take it and show it the way to the $buf variable. So, we now have that data in $buf and can send back a nice reply on lines 57 through 61. Again, $msgsock will take care of this, and $sock will just open and close the hatch.
The last thing we do in this script is tell both men, $sock and $msgsock to go home and take a rest (lines 64 and 67). Or in more technical terms, we close both sockets and the network connection.
Testing our TCP server
Okay, it's time for testing -- always the most exciting part. However, before you try to execute the script, make sure you have the right permissions on it:
chmod 755 lst01.php
Also make sure that the first line of the script points at your PHP binary. Then, start the server:
./lst01.php
(If you get an error saying that the socket() function is undefined, you need to get into your PHP source directory, run ./configure --enable-sockets, and then recompile and reinstall the PHP binary by running make && make install.)
Now, open another terminal, and issue the following command:
telnet 0 10000
This means you want to establish a telnet connection to your local machine, and you want to use port 10000. If everything is okay, you should now get the following output:
Trying 0.0.0.0...
Connected to 0.
Escape character is '^]'.
Welcome to my TCP server!
Now, write someting and press enter:
Hello
You said: Hello
Connection closed by foreign host.
Isn't that cool? It's not very advanced, but we actually created a real network connection and exchanged some information through it.
Summary
In this article, you learned how to exchange data between two computers using network sockets. I hope you found the figures and explanations useful. The key to becoming a successful programmer is to understand what is actually happening behind a certain function call. When you can do that, you will be able to truly take control of your program.
Remember, network programming is all about sending and receiving data over a network connection. We did both today, so what's stopping you?
Daniel Solin is a freelance writer and Linux consultant whose specialty is GUI programming. His first book, SAMS Teach Yourself Qt Programming in 24 hours, was published in May, 2000.
Discuss this article in the O'Reilly Network PHP Forum.
Return to the PHP DevCenter.
You must be logged in to the O'Reilly Network to post a talkback.
Showing messages 1 through 28 of 28.
-
Page loading when using sockets
2006-12-19 21:50:31 Hassanur [Reply | View]
Hi,
I m a final year graduate student. I m going to implement Bandwidth Manager as my Final year project. I m creating socket connection with my clients. The web page waits untill any connection is established & no page contents are shown untill socket_listen. I want my page to display very soon & engine to wait for socket_listen & socket_accept will continously run. I used ob_flush( ) and flush ( ) but doesn't work....
What should I do ??
-
error on tcp-server testing
2006-05-16 06:13:31 dlphsharma123 [Reply | View]
when i was tried to do #telnet 0 10000
error:
telnet: connecting to address 0.0.0.0: connection refused
telnet: unable to connect to remote host: connection refused
tell me what to do because i'm new for socket prg.
-
Testing our proxy
2005-03-04 09:34:18 aleppos [Reply | View]
hi,
i try to connect to the socket like http://mysite.net:10000
but because i am using a proxy i can't coonect to the port 10000 can you help me please
if you can please send to me email at aleppos20@hotmail.com
i wait your replay thanks
-
socket in Windows
2004-01-11 01:23:30 anonymous2 [Reply | View]
Hi!
This is a jump start for my socket pgming which I was dreaming to do in C.
Anyway, I have a problem with socket() function in Windows. As you mentioned it says socket function is undefined.. But I couldnt follow the way u told to edit the php source. Could you please be a little more elaborate. Thankyou
TommYNandA -
socket in Windows
2004-09-03 23:15:39 vinukrish [Reply | View]
Dear,
Please tell which version of PHP ur using on windows platform.I have solution of ur problem
Follow these steps :
> check ur php.ini file .in this check dynamic extensions section please uncomment the line extension=php_sockets.dll
> secondly now in ur php folder find ext folder copy php_sockets.dll file to ur windows folder and system folder.
Now ur script is ready to use socket function on windows platform.
Have a nice socket programming...
-
One char only
2003-11-29 10:55:00 anonymous2 [Reply | View]
Thank you for the useful article.
On Windows XP, PHP 4.3.3, when I connect with telnet (windows native) I can write only a character and then the connetcion will close...why?
Thx for the answer... -
One char only
2004-01-27 00:25:39 yamakazi [Reply | View]
On PHP.net a post reads:
'Be carefull, with PHP 4.3.x on Windows, the socket_read function does not works. (bug post on 12/26/2002...)'
I had the same problem as you and this guy is right. I wrote a socket programm and tested it on Windows and it didn't work. I tried the same script on Debian and it worked fine.
-
A nice one.
2003-08-07 15:08:43 inkaytown [Reply | View]
Hello Daniel,
First of all thanks for a very comprehensible intro to PHP socket server programming.I've couple of questions to ask and I see the forums are closed.So, heres my first one.After the connection is established,i telnet to send some string.As soon as I enter the first character, it closes the connection.In the article, it says the connection would be lost after I press enter.
why does this does'nt work with me??
Thanks for your time
-
Socket Programming
2003-07-10 07:50:32 anonymous2 [Reply | View]
I found it very helpfull to understand the concept of socket programming and now I'm going to try to develop my solution. (-:
Chris
-
Socket Client problem
2003-01-30 04:40:58 manjay_dwivedi [Reply | View]
I am trying to write the socket client(which i want to run by browser).I am able to successfully connect to Socket server but i dont know how to send that data to server & read from server.Here is my code which do the connectivity part of it.can someone tell me the solution of this?
<?php
$host = "localhost";
$port = 10000;
$timeout = 45;
$fp = fsockopen($host, $port, $errno,
$errstr, $timeout);
if(!$fp)
{
echo $errstr . "Errno:" .
$errno . "<br>";
}
else
{
echo "socket successfully opened";
}
fclose($fp);
?>
THNX in advance
Manjay
-
Re: unable to run this script
2003-01-25 10:05:42 dsolin [Reply | View]
Hi there,
Could you please specify exactly what problem you have? If we could see the error messages you get, it would be much easier to help out.
If you needed general information about running PHP scripts, see this URL:
http://www.php.net/manual/en/installation.php
All best,
Daniel -
Re: unable to run this script
2003-01-29 22:53:09 manjay_dwivedi [Reply | View]
Hi Daniel
See i'm able to run this script through telnet
using command php sock.php
but how i run this script through browser.
Regards
Manjay
-
Re: unable to run this script
2003-01-29 23:00:54 dsolin [Reply | View]
Hi again,
Take a look at one of the articles here at ONLamp that covers the PHP installation process:
http://www.onlamp.com/pub/a/php/2000/11/17/php_admin.html
http://www.onlamp.com/pub/a/php/2000/12/14/php_admin.html
http://www.onlamp.com/pub/a/php/2001/03/15/php_admin.html
http://www.onlamp.com/pub/a/php/2001/04/26/php_admin.html
Good luck!
-Daniel -
Re: unable to run this script
2003-01-26 22:20:59 manjay_dwivedi [Reply | View]
see how i'm trying to run this script
i put this script in my /var/www/html/sock/
folder
when i trying to run this through command line
./sock.php
it's shwing me error --no such directory or file found
but the file is exist in that directory
i'm using PHP ver-4.0 and Apachi server on linux .
could u plz tell wat the exact way .
Regards
Manjay
-
Re: unable to run this script
2003-01-26 23:03:12 dsolin [Reply | View]
Hi again!
Given that /var/www/html is your web root, you can either run the script by making a usual HTTP request:
http://localhost/sock/sock.php
Or, you can (is you indicate above) run it via the command-line. However, to do this you must have PHP as a binary (a program that can interpret PHP code). If you don't know if you have this, try the following:
root@localhost# cd /var/www/html/sock
root@localhost# php sock.php
If this get the script executed, you're safe. If it returns a "php: command not found", you need to install/compile a PHP binary.
When you do have a PHP binary, you can also add a so-called "shebang" at the top of your script:
#!/path/to/php
and then do a 'chmod 755 sock.php' to make it executable. By this, you will be able to run the script by just typing its name on the command-line:
root@localhost# cd /var/www/html/sock
root@localhost# ./sock.php
Hope this helps!
Best,
Dan -
Re: unable to run this script
2003-01-29 03:11:42 manjay_dwivedi [Reply | View]
thankx a lot dear
now i'm enable to run the script.
thanx a lot 4 coopration.
-
Re: unable to run this script
2003-01-29 02:45:00 manjay_dwivedi [Reply | View]
how i find where is the binary of php on my linux server.
Is the default path is --/usr/local/bin/
yeah i got error when i trying to run php sock.php
it's giving me command not found error .
wat i should do ,where is the fault.
plz try to solve the problem.
Regards
Manjay -
Re: unable to run this script
2003-01-29 02:51:12 dsolin [Reply | View]
Hi again,
Did you compile and install PHP from source? If so, recompile it but this time run the configure-script without the --with-apxs switch:
cd <php-src-dir>
./configure --prefix=/usr/local
make
This should generate a php binary (a file called 'php') in your <php-src-dir>. Simply copy this file to /usr/local/bin:
cp php /usr/local/bin
If you installed PHP from a binary package, try to find a CGI-version of the package, and install that one. What Linux distribution do you use?
Best,
Daniel
-
unable to run this script
2003-01-24 23:42:30 manjay_dwivedi [Reply | View]
Dear sir
unable to run this script .
Could any one help to run this program plz
where i should keep this file .
plz giude me dear.
Regards
Manjay
-
Function names changed
2002-12-04 16:56:30 anonymous2 [Reply | View]
Nice article.. for anyone trying out this example script.. the function names have changed. All function are now prepended by socket_.. (socket_create, socket_bind, socket_listen, socket_accept, socket_write, socket_read and socket_close). Also socket read only accepts 2 arguments now.. so change $ret = read($msgsock, $buf, 128) into $buf = read($msgsock, 128).
-
very helpful. But I have one more question....?
2002-10-10 17:40:30 anonymous2 [Reply | View]
How to write interactive application which can be viewed in web browser with PHP?
your kindly response can sent to my email address:
busycity@hotmail.com.
Thank you very much!
Sheerong Du
-
Outstanding Article!
2002-10-09 07:05:16 anonymous2 [Reply | View]
This article is clear and VERY easy to understand and follow! Thank you!!!
-Travis
-
cool article
2002-09-11 05:29:53 anonymous2 [Reply | View]
thx for the article.
I learned from it. And eh... 'bout the drawings... http://www.drawbooks.com/drawbooks.htm :-)
Wilbert
-
Can't view listing1.html
2001-05-21 02:35:55 petermason [Reply | View]
Hi there,
The article really looks nice and it's just about something what I'm playing around with. It would be very helpfull though when it would be possible to view the example listing 1. When trying to access it, ti just gives out an error message...
hope you can change that,
cheers,
peter



Thanks
AK