Advertisement
aaaaaa123456789

PHP socket server testing code

Nov 7th, 2013
91
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. require "server.php"; // I called the socket server file this
  4.  
  5. $clients = array();
  6.  
  7. function onConnection ($client, $server) {
  8.   global $clients;
  9.   $clients[$client] = false;
  10.   $server -> send($client, "Please enter your name: ");
  11. }
  12.  
  13. function onClose ($client, $server) {
  14.   global $clients;
  15.   $name = $clients[$client];
  16.   unset($clients[$client]);
  17.   if ($name === false) return; // if it never gave us a name, we don't care
  18.   $server -> broadcast("$name disconnected", 0, SERVER_SEND_LINE_CRLF);
  19. }
  20.  
  21. function onMessage ($message, $client, $server) {
  22.   global $clients;
  23.   if ($clients[$client] === false) {
  24.     $clients[$client] = $message; // first message is the name
  25.     $server -> broadcast("$message connected", - $client, SERVER_SEND_LINE_CRLF);
  26.     // and we tell everyone else this person connected
  27.     return;
  28.   }
  29.   $name = $clients[$client];
  30.   $server -> broadcast("$name: $message", - $client, SERVER_SEND_LINE_CRLF);
  31.   // we send the message to everyone but the guy who sent it
  32. }
  33.  
  34. function setupServer () {
  35.   $server = new Server();
  36.   $server -> splitMode = SERVER_SPLIT_NEWLINES_NO_BLANKS; // we split on Enters
  37.   $server -> openCallback = "onConnection";
  38.   $server -> closeCallback = "onClose";
  39.   $server -> receiveCallback = "onMessage";
  40.   return $server;
  41. }
  42.  
  43. $myServer = setupServer();
  44. $myServer -> open(46464); // choose any port you like
  45.  
  46. ?>
Advertisement
RAW Paste Data Copied
Advertisement