PHP
  Home arrow PHP arrow Page 3 - 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 - Reading and writing socket data: creating a simple web-based client application
    ( Page 3 of 4 )

    Creating a client application to test the sample TCP server is a straightforward task. Essentially, I'll build a web-based script that will connect to the aforementioned server and send a string of data via an online form. In accordance with the logic implemented on the server, this string should be returned to the client in uppercase, and finally displayed on the browser.

    Here's the snippet of code that creates a simple web-based client, handy for testing the TCP server in question:

    <?php
    // check if form was submitted
    if($_POST['send']){
        // open client connection to TCP server
        if(!$fp=fsockopen('127.0.0.1',1234,$errstr,$errno,30)){
            trigger_error('Error opening socket',E_USER_ERROR);
        }
        $message=$_POST['message'];
        // write message to socket server
        fputs($fp,$message);
        // get server response
        $ret=fgets($fp,1024);
        // close socket connection
        fclose($fp);
        echo '<h1>You entered the following message in
    lowercase :'.$ret.'</h1>';
        exit();
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>TESTING TCP SOCKET SERVER</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    </head>
    <body>
    <h1>Enter your message here</h1>
    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
    <input type="text" name="message" size="30" /><br />
    <input type="submit" name="send" value="Send Value" />
    </form>
    </body>
    </html>

    As you can appreciate, the above script uses the PHP "fsockopen()" function, in order to connect to the recently created TCP server and inject into the socket the string entered in the online form. After receiving the uppercase string, the script displays this data and finishes its execution.

    To understand the functionality of the sample TCP server, please take a look at the following screen shots, which illustrate both the client petition and the server response respectively:

    As depicted above, the images show the TCP server in action. First, the client submits a message via the online form, and secondly the server turns the input to an uppercase string, which is finally echoed to the browser.

    In addition, before I explain more concepts related to socket programming in PHP, I want to clarify one important point regarding the example: you should run the script that creates the TCP server from the PHP command line, instead of using your browser, in order to prevent the system from hanging. This can be done easily by using the CLI.exe file that comes with your PHP distribution and typing the following commands in your system shell:

    q- tcpserver.php

    The following screen shot shows how to start the TCP server using the PHP command line on a Windows system:

    Assuming that the TCP server has been coded in a file called "tcpserver.php," the above command should run this file and start the server (the preceding q flag tells the PHP interpreter to suppress the "Content-type" HTTP header). After making sure the server is up and running, you can point your browser to the PHP file that builds the corresponding client, and run the pertinent file.

    Right, now you see how the sockets I created in the previous section do their job, reading and writing the corresponding data. Since the example TCP server has been created with a few lines of procedural code, it'd be very convenient to encapsulate the whole source code within a compact function (and incidentally within a class), so the server can be reused as many times as needed.

    If you're interested in learning how this can be achieved, please read the next few lines of the article.



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