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  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PHP

An Introduction to Sockets in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 24
    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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek