Search code examples
javaphpsocketssocketserver

PHP Socket Server for multiple clients


Possible Duplicate:
A PHP Socket Server with Flash Clients

I am building an app in my server with the help of a flash developer, and he asked me to build a socket server to communicate with the database. He recommended me JAVA but I am not very good at JAVA and I was wondering if it was possible to build a Socket Server in PHP.

I should allow connections to multiple TCP client connections. I know in JAVA this is done thought threading, but I am not sure if this can also be achieved with PHP.

Could someone please show me the basic skeleton of a PHP Socket Server with these characteristics?

The connection has to be TCp (persistent) from the beginning of the connection to the app, until the end.


Solution

  • You have to run your socket server as a service from the command line. This is a part of what I have used before. It closes the socket after a read but can easy be modified to keep a array of connections.

    • You would have to build some kind of watchdog to see if a connection is still alive.
    • You need a identifying mechanism to identify different connections.

    The code:

    set_time_limit( 0 );
    // Set the ip and port we will listen on
    $address = '127.0.0.1';
    $port = 6789;
    
    // Create a TCP Stream socket
    $sock = socket_create( AF_INET, SOCK_STREAM, 0 ); // 0 for  SQL_TCP
    // Bind the socket to an address/port
    socket_bind( $sock, 0, $port ) or die( 'Could not bind to address' );  //0 for localhost
    // Start listening for connections
    socket_listen( $sock );
    
    //loop and listen
    while (true) {
      /* Accept incoming  requests and handle them as child processes */
      $client = socket_accept( $sock );
      // Read the input  from the client – 1024000 bytes
      $input = socket_read( $client, 1024000 );
    
      // from here you need to do your database stuff
      // and handle the response 
    
       // Display output  back to client
      socket_write( $client, $response );
      socket_close( $client );
    }
    // Close the master sockets
    socket_close( $sock );