PHP
  Home arrow PHP arrow Page 4 - 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 - Reusing the TCP server: defining the "createSocketServer()" function and "SocketServer" class


    (Page 4 of 4 )

    As I said in the previous section, it'd be really handy to encapsulate the full code for creating the sample TCP server into one single function. The function would perform basically the same task, but have the advantage of making the code much more compact and reusable. Bearing in mind this concept, here's the definition for the corresponding "createSocketServer()" function:

    function createSocketServer($host='127.0.0.1',$port=1234){
        if(!preg_match("/^d{1,3}.d{1,3}.d{1,3}.d{1,3}
    $/",$host)){
            trigger_error('Invalid IP address format.',E_USER_ERROR);
        }
        if(!is_int($port)||$port<1||$port>65535){
            trigger_error('Invalid TCP port number.',E_USER_ERROR);
        }
        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);
        }
        // bind 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 shown above, I hid all the complexities of creating the socket server, as well as reading, processing and returning client data in just one function, which I called "createSocketServer." This function does basically the same thing as the previous script, and introduces some additional checking code, in order to make sure that the two incoming arguments, that is the IP address and the TCP port respectively, have a valid format.

    Now, creating the previous TCP server could be reduced to a process as simple as this:

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

    I told you it was simple! Again, remember first to save this function to a file and next run it from the PHP command line (also, it's possible to connect to the TCP server by using a Telnet client), in order to get things working appropriately.

    Now that you know how the "createSocketServer()" function works, please have a look at the following PHP snippet, which encapsulates all the source code required for building the prior TCP server in one class:

    class SocketServer{
        var $host;
        var $port;
        function  SocketServer($host='127.0.0.1',$port=1234){
            if(!preg_match("/^d{1,3}.d{1,3}.d{1,3}.d{1,3}
    $/",$host)){
                trigger_error('Invalid IP address
    format.',E_USER_ERROR);
            }
            if(!is_int($port)||$port<1||$port>65535){
                trigger_error('Invalid TCP 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);
            }
            // bind 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);
            }
            // 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);
        }
    }

    In this case, I turned the "createSocketServer()" function into a fully working PHP class, thus if you feel inclined to work with object-oriented applications, this class could be quite appealing to you.

    After building the "SocketServer" class, creating and using the prior TCP server can be reduced to the following two-liner:

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

    That's it. In this article I've shown you different flavors of the same TCP server, according to your programming needs, so I guess there's enough code to provide you with long hours of fun!

    To wrap up

    Over this first part of the series, you hopefully learned the basics of how to create sockets in PHP, as well as read, process and write socket data through an instructive example, aimed at building a simple TCP server. However, there's still a huge area to be explored. Bearing this in mind, in the next article, I'll show you how to use low-level sockets, in order to build a "smarter" and more complex TCP server. You won't want to miss it!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · 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 5 hosted by Hostway
    Stay green...Green IT