PHP
  Home arrow PHP arrow Page 3 - Developing an Extensible TCP Server with 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

Developing an Extensible TCP Server with Sockets in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 14
    2006-05-30


    Table of Contents:
  • Developing an Extensible TCP Server with Sockets in PHP
  • A quick look at the previous TCP server
  • Expanding the original TCP server: processing multiple client requests
  • Defining the createSocketServer() function and the 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


    Developing an Extensible TCP Server with Sockets in PHP - Expanding the original TCP server: processing multiple client requests
    ( Page 3 of 4 )

    Once you've learned how to create a low-level socket in PHP, in conjunction with reading and writing socket data, expanding the previous TCP server is a fairly standard process. Basically I'm not going to introduce new terms or concepts to achieve the new desired functionality.

    In short, what I'll do next is change the original procedural script and introduce a simple loop structure, in order to provide the server with the ability to keep running over and over again, attending to multiple client requests, until it is deliberately stopped.

    Here is the source code for the improved TCP server, now capable of processing many requests:

    // define  TCP port & local host
    $port=12345;
    $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);
    }
    $message='This is a simple TCP/IP server created with PHP
    sockets!'."rn";
    socket_write($comSocket,$message,strlen($message));
    // start a loop and continue reading user input
    do{
        // delay loop execution
        sleep(10);
        // read socket input
        $socketInput=socket_read($comSocket,1024);
        if(trim($socketInput)!=''){         
            // if user did not entered the 'STOP" command continue
    reading data
            if(trim($socketInput)!='STOP'){
                // build socket output 
                $socketOutput='The string you entered was
    '.$socketInput."rn";
                // write data back to socket server
                socket_write($comSocket,$socketOutput,strlen
    ($socketOutput));
                echo 'The string you entered is '.$socketOutput;
            }
            else{
                // if 'STOP' command was entered close communication
    socket & terminate all the connections
                socket_close($comSocket);
                break;
            }
        }
    }
    while(true);
    // close global socket
    socket_close($socket);

    Even though the script shown above is closely similar to the one I wrote in the first part of this series, it also exposes some differences worth mentioning. First, please notice the inclusion of the "do-while" loop, in order to keep the server listening over and over for incoming client connections.

    Second, the server will display a simple welcome message, and will only stop listening for requests when the client sends out the "STOP" command. If this happens, the loop is halted and both the general and communication sockets are properly closed.

    Additionally, in this example, I slightly modified the behavior of the server, so each time the client transmits a string, it will be redisplayed to the client. Of course, there's plenty of room to experiment here, and certainly you may want to change the source code in order to make the server perform a more useful task.

    Now, take a look at the following screen shots, which depict the whole client-server interaction process using a Microsoft Telnet client:

    As you can see on the above images, after starting the server from the PHP command line, I used a simple Telnet client (like Microsoft's) and made some requests to it, by entering different strings. In all cases, the server displayed the inputted string in the console, and only stopped working when I entered the "STOP" command.

    In this example, hopefully you could see how data comes in and out through the communication channel established between the server and the client. Simple and educational, isn't it?

    At this point, I hope you've already grasped the driving logic for creating a TCP server, which now processes multiple requests from a specific client, by using some socket programming PHP functions.

    Therefore, come with me and read the last section of the article, in order to learn how to translate the procedural script you saw before into a compact and reusable function, and an additional PHP class.



     
     
    >>> 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 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek