PHP
  Home arrow PHP arrow Page 2 - Emulating a Basic Web 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

Emulating a Basic Web Server with Sockets in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 7
    2006-06-05


    Table of Contents:
  • Emulating a Basic Web Server with Sockets in PHP
  • Taking a quick look at the previous TCP server
  • Emulating a Web server
  • Putting the Web server to work

  • 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


    Emulating a Basic Web Server with Sockets in PHP - Taking a quick look at the previous TCP server
    ( Page 2 of 4 )

    Before I start coding the Web server, I’d like you to recall how the previous TCP server was developed. Since the Web server I plan to build will use most of the PHP functions that you learned in the previous installments, you shouldn’t have any problems understanding how it will work.

    That said, here is the full source code that corresponds to the previous TCP server, including both procedural and object-oriented approaches:

    /*
    /****************************************************************
    / procedural script for building a multi-request TCP server
    /****************************************************************
    */

    // 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 comunication 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!'."\r\n";
    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."\r\n";
                // 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);

    /*
    /****************************************************************
    / 'createSocketServer()' function for building a multi-request
    TCP server
    /****************************************************************
    */
    function createSocketServer($host='127.0.0.1',$port=12345){
        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!'."\r\n";
        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'){
                    // convert to uppercase socket input 
                    $socketOutput='The string you entered was
    '.$socketInput."\r\n";
                    // 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);
    }

    /*
    /**************************************************************
    /  'SocketServer()' class for creating a multi-request TCP server
    /**************************************************************
    */
    class SocketServer{
        var $host;
        var $port;
        var $delay=10;
        var $message="This is a simple TCP/IP server created with PHP
    sockets!\r\n";
        function SocketServer($host='127.0.0.1',$port=12345){
            if(!is_int($port)||$port<1||$port>65535){
                trigger_error('Invalid port number',E_USER_ERROR);
            }
            $this->host=$host;
            $this->port=$port;
            $this->connect();
        }
        function connect(){
            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,$this->host,$this->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);
            }
            socket_write($comSocket,$this->message,strlen($this-
    >message));
            // start a loop and continue reading user input
            do{
                // delay loop execution
                sleep($this->delay);
                // 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'){
                        $socketOutput='The string you entered was
    '.$socketInput."\r\n";
                        // 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);
        }
    }

    Right, as you can see, I listed above the complete source code for implementing a multi-request TCP server, including a raw procedural script, and of course adding the corresponding “createSocketServer()” function and the “CreateSocket” PHP class. Whether you’re using a procedural approach or an object-based method for coding your applications, I’m sure that one of the above listed implementations of the pertinent TCP server will meet your particular needs.

    Now that I reminded you of how a multi-request TCP server can be created, join me in the next section, in order to learn how to emulate a basic Web server on your own testing machine. Go ahead and read the next section.



     
     
    >>> 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