PHP
  Home arrow PHP arrow Page 2 - An Introduction to Sockets in PHP
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

An Introduction to Sockets in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 21
    2006-05-22

    Table of Contents:
  • An Introduction to Sockets in PHP
  • The basics of low-level sockets: developing an illustrative example
  • Reading and writing socket data: creating a simple web-based client application
  • Reusing the TCP server: defining the "createSocketServer()" function and "SocketServer" class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    An Introduction to Sockets in PHP - The basics of low-level sockets: developing an illustrative example


    (Page 2 of 4 )

    In order to introduce the core concepts of socket programming in PHP in a friendly way, I'm going to set up a basic example, which hopefully will help to illustrate the usage of the most important socket-related PHP functions. First I'll show you how to develop a simple TCP server with sockets, and then I'll explain the meaning of each function used in the sample script.

    Having said that, here's a procedural script that builds a basic TCP server. Take a look at the code listed below:

    // define TCP port & local host
    $port=1234;
    $host='127.0.0.1';
    set_time_limit(0);
    // create low level socket
    if(!$socket=socket_create(AF_INET,SOCK_STREAM,0)){
        trigger_error('Error creating new socket',E_USER_ERROR);
    }
    // tie up socket to TCP port
    if(!socket_bind($socket,$host,$port)){
        trigger_error('Error binding socket to TCP
    port',E_USER_ERROR);
    }
    // begin listening connections
    if(!socket_listen($socket)){
        trigger_error('Error listening socket
    connections',E_USER_ERROR);
    }
    // create communication socket
    if(!$comSocket=socket_accept($socket)){
        trigger_error('Error creating communication
    socket',E_USER_ERROR);
    }
    // read socket input
    $socketInput=socket_read($comSocket,1024);
    // convert to uppercase socket input
    $socketOutput=strtoupper(trim($socketInput))."n";
    // write data back to socket server
    if(!socket_write($comSocket,$socketOutput,strlen($socketOutput))){
        trigger_error('Error writing socket output',E_USER_ERROR);
    }
    // close sockets
    socket_close($comSocket);
    socket_close($socket);

    As you can see, the procedural script listed above demonstrates how to create a simple TCP server, where its only functionality rests in taking up a string sent by a client, then converting it to its uppercase version and finally returning it to the mentioned client. Does that sound a little bit confusing? Don't worry, it really isn't.

    First, the script defines the host and port number where the TCP server will be running. In this specific case the server will be created to work as "localhost," that is its IP address will be 127.0.0.1 and it will run on the TCP port "1234."

    After defining the corresponding connection parameters, the first connection socket is created by the "create_socket()" PHP built-in function, which obviously creates and returns a socket reference. Also, the first argument of this function--that is the domain parameter--specifies the protocol family to be used by the socket, in this case AF_INET, which means that it will use the IPv4 Internet-based protocols.

    Additionally, the second argument indicates the type of socket to be used. In this example, I specified a value of "SOCK_STREAM," meaning that the socket will support the use of the TCP protocol. Finally, the last function parameter determines the protocol used by the socket. In this case I decided to use the reliable TCP protocol.

    Of course, all the above description can be assumed in the following statement:

    // create low level socket
    if(!$socket=socket_create(AF_INET,SOCK_STREAM,0)){
        trigger_error('Error creating new socket',E_USER_ERROR);
    }

    Right, after creating the general connection socket, the script needs to bind it to the host and port defined before. To perform this operation, the "socket_bind()" function is conveniently used, as listed below:

    // tie up socket to TCP port
    if(!socket_bind($socket,$host,$port)){
        trigger_error('Error binding socket to TCP
    port',E_USER_ERROR);
    }

    At this point, I created a general connection socket, which is tied to the 127.0.0.1 IP address, and will be expecting incoming connections on the TCP port 1234. Now, how do I make the socket listen to client connections? Right, you guessed it,  the "socket_listen()" function does precisely that:

    // begin listening connections
    if(!socket_listen($socket)){
        trigger_error('Error listening socket
    connections',E_USER_ERROR);
    }

    Now that the general connection socket has been created and it's expecting client connections, there are a few additional things to be done yet. The first one consists of creating another communication socket, which will handle all the operations for reading and writing data. This is achieved by the "socket_read()" and "socket_write()" PHP functions respectively, and the entire reading-writing sequence is illustrated below:

    // read socket input
    $socketInput=socket_read($comSocket,1024);
    // convert to uppercase socket input
    $socketOutput=strtoupper(trim($socketInput))."n";
    // write data back to socket server
    if(!socket_write($comSocket,$socketOutput,strlen($socketOutput)))
    {
        trigger_error('Error writing socket output',E_USER_ERROR);
    }

    As you can see, the above code block first reads the data sent by the client, then converts the data to uppercase and writes the string back to the client. At the end of this process, both sockets, the general and the communication one, are closed by the "socket_close()" PHP function, as shown below:

    // close sockets
    socket_close($comSocket);
    socket_close($socket);

    Wasn't that simple and fun? With a few PHP functions, I created an admittedly basic TCP server that returns the uppercase version of any string sent out by the client.

    Also, before I finish writing this section, I'd like you to notice that the script uses the "set_time_limit()" function, in order to get rid of any timeouts imposed by the PHP parser. This makes a lot of sense, since the script doesn't have a clue about when an eventual client is going to inject data into the socket, so eliminating timeouts is a good approach to keep the script working properly.

    Now, the sample TCP server is up and running, listening to incoming client connections. Therefore, a client application should be created, in order to determine whether the sockets just created work as expected. That's exactly what I'll do in the next section, thus click on the link below to find out how this client is created.

    More PHP Articles
    More By Alejandro Gervasio


       · This first article covers the most important functions related to creating,...
       · This one is the best tutorial i found on net.Good Work
       · Thank you for the kind comments on my PHP article. I really appreciate them and it's...
       · i comment over this topic previously it was great.i am using your server ex. to...
       · Thank you for commenting on my PHP article. Actually, I’m not sure to understand...
       · I was looking for an introduction of PHP network programming capabilities as I...
       · Thanks for the kind words on my PHP sockects article. Good to know it's been helpful...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT