Home arrow PHP arrow Page 4 - Developing an Extensible TCP Server with Sockets in PHP

Defining the createSocketServer() function and the SocketServer class - PHP

Are you interested in learning how to manipulate low-level sockets in PHP? Your search has finished. This is the second part of the series “Handling sockets in PHP,” and hopefully you’ll find in it valuable material regarding the creation and manipulation of sockets with PHP, in conjunction with numerous illustrative hands-on examples that will help you build socket servers in a few easy steps.

TABLE OF CONTENTS:
  1. Developing an Extensible TCP Server with Sockets in PHP
  2. A quick look at the previous TCP server
  3. Expanding the original TCP server: processing multiple client requests
  4. Defining the createSocketServer() function and the SocketServer class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 16
May 30, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Since I already showed you how to use a procedural script for creating a multi-request TCP server, I'll now list different versions of the same application, just in case you want to work with a reusable function or, specifically in the object-based area, with a PHP class. Here are the respective definitions for both approaches:

/*
/**************************************************************
/ 'createSocketServer()' function
/**************************************************************
*/
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!'."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'){
                // convert to uppercase socket input 
                $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);
}

/*
/*************************************************************
/  'SocketServer()' class
/*************************************************************
*/
class SocketServer{
    var $host;
    var $port;
    var $delay=10;
    var $message="This is a simple TCP/IP server created with PHP
sockets!rn";
    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."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);
    }
}

In the first case, if you're going to use the "createSocketServer()" function, this one can be used like this:

// call 'createSocketServer()" function
createSocketServer();

Or, in case you prefer to work with an object-oriented approach, the "SocketServer" class can be utilized as follows:

// instantiate 'SocketServer' object
$sock=&new SocketServer();

To wrap up

That's all for the moment. In this second part of the series, I've shown you how to build an extensible TCP server that handles multiple incoming requests, using the PHP socket-related functions that you learned in the first tutorial. But, do you think that's all? Nope; in the last article, I'll demonstrate how to implement a Web server on your own machine, by utilizing a few low-level sockets. You don't have any excuses to miss it!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: