initial commit
initial commit

file:b/index.html (new)
--- /dev/null
+++ b/index.html
@@ -1,1 +1,126 @@
-
+<!DOCTYPE html>

+<html>

+<head>

+<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

+

+<script>

+$(document).ready(function() {

+

+  if(!("WebSocket" in window)){

+  $('#chatLog, input, button, #examples').fadeOut("fast");

+  $('<p>Oh no, you need a browser that supports WebSockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');

+  } else {

+      connect();

+

+      function connect(){

+          var socket;

+          var host = "ws://192.168.0.2:10001/";

+

+          try{

+              var socket = new WebSocket(host);

+

+              message('<p class="event">Socket Status: '+socket.readyState);

+

+              socket.onopen = function(){

+                 message('<p class="event">Socket Status: '+socket.readyState+' (open)');

+              }

+

+              socket.onmessage = function(msg){

+                 message('<p class="message">Received: '+msg.data);

+              }

+

+              socket.onclose = function(){

+                message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');

+              }

+

+          } catch(exception){

+             message('<p>Error'+exception);

+          }

+

+          function send(){

+              var text = $('#text').val();

+

+              if(text==""){

+                  message('<p class="warning">Please enter a message');

+                  return ;

+              }

+              try{

+                  socket.send(text);

+                  message('<p class="event">Sent: '+text)

+

+              } catch(exception){

+                 message('<p class="warning">');

+              }

+              $('#text').val("");

+          }

+

+          function message(msg){

+            $('#chatLog').append(msg+'</p>');

+          }

+

+          $('#text').keypress(function(event) {

+              if (event.keyCode == '13') {

+                send();

+              }

+          });

+

+          $('#disconnect').click(function(){

+             socket.close();

+          });

+

+      }//End connect

+

+  }//End else

+

+});

+</script>

+

+<style type="text/css">

+body {

+    font-family:Arial, Helvetica, sans-serif;

+}

+#container{

+    border:5px solid grey;

+    width:800px;

+    margin:0 auto;

+    padding:10px;

+}

+#chatLog{

+    padding:5px;

+    border:1px solid black;

+}

+#chatLog p {

+    margin:0;

+}

+.event {

+    color:#999;

+}

+.warning{

+    font-weight:bold;

+    color:#CCC;

+}

+</style>

+

+<title>WebSockets Client</title>

+

+</head>

+<body>

+<div id="wrapper">

+

+    <div id="container">

+

+        <h1>WebSockets Client</h1>

+

+        <div id="chatLog">

+

+        </div>

+        <p id="examples">e.g. try 'ping'</p>

+

+        <input id="text" type="text" />

+        <button id="disconnect">Disconnect</button>

+

+    </div>

+

+</div>

+</body>

+</html>​

--- /dev/null
+++ b/server.functions.php
@@ -1,1 +1,127 @@
+<?php
 
+function sendMesageToYou ($socket, $msg, $handshake=false) {
+	$msg = $msg;
+	echo "[".date('Y-m-d H:i:s')."] MESSAGE to ".intval($socket)." ".$msg.")\n";
+	if ( $handshake == false ) {
+		@socket_write ($socket, encode($msg));
+	} else {
+		@socket_write ($socket, $msg, strlen($msg));
+	}
+}
+
+function sendMessageToAll ($allclients, $session, $msg) {
+	global $_sockets;
+	foreach ($allclients as $client) {
+		if ( $_sockets[$client]['session'] == $session ) {
+			echo "[".date('Y-m-d H:i:s')."] MESSAGE to ".intval($client)." ".$msg.")\n";
+			@socket_write ($client, encode ($msg));
+		}
+	}
+}
+
+function send_Msg($allclients,$socket,$id,$msg) {
+	global $_sockets;
+
+	if (!empty($_sockets[intval($socket)])) {
+		$nicks = array(); //amig fut a parancs ebben vannak a nickek.
+
+		foreach ($_sockets as $_socket){
+			foreach ($_socket as $key=>$val){
+				// this check's the onliners
+				if (empty($nicks[$val])) $nicks[$val]=1;
+				else $nicks[$val]=$nicks[$val]+1; // we shouldn't have duplicated nicks, but what if...
+			}
+		}
+
+		foreach($allclients as $client) {
+			if (!empty($_sockets[$client]['nick']) && ($_sockets[$client]['nick'] == $id)) {
+				$_client = $client;
+				$out = "<msg aid=\"".$_sockets[$socket]['nick']."\" time=\"".date("H:i:s")."\" msg=\"".$msg."\" from=\"".$_sockets[$client]['nick']."\" />";
+			}
+			elseif(empty($nicks[$id])) {
+				//backto the sender
+				$_client = $socket;
+				$out = "<error value=\"User is already left.\"/>";
+			}
+		}
+	} else {
+		//backto the sender
+		$_client = $socket;
+		$out = "<error value=\"Not identified.\"/>";
+	}
+	if (!empty($out)) {
+		socket_write($socket, $out.chr(0)); //send to back ourself. we have to handle it in flash
+		socket_write($_client, $out.chr(0)); //send to the recipient
+	}
+}
+
+
+function dohandshake($socket, $buffer) {
+	// Determine which version of the WebSocket protocol the client is using
+	if(preg_match("/Sec-WebSocket-Version: (.*)\r\n/ ", $buffer, $match))
+	    $version = $match[1];
+	else
+	    return false;
+
+	if($version >= 8){
+	    // Extract header variables
+	    if(preg_match("/GET (.*) HTTP/"   ,$buffer,$match)){ $r=$match[1]; }
+	    if(preg_match("/Host: (.*)\r\n/"  ,$buffer,$match)){ $h=$match[1]; }
+	    if(preg_match("/Sec-WebSocket-Origin: (.*)\r\n/",$buffer,$match)){ $o=$match[1]; }
+	    if(preg_match("/Sec-WebSocket-Key: (.*)\r\n/",$buffer,$match)){ $k = $match[1]; }
+
+	    // Generate our Socket-Accept key based on the IETF specifications
+	    $accept_key = $k . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
+	    $accept_key = sha1($accept_key, true);
+	    $accept_key = base64_encode($accept_key);
+
+	    $upgrade =  "HTTP/1.1 101 Switching Protocols\r\n" .
+	                    "Upgrade: websocket\r\n" .
+	                    "Connection: Upgrade\r\n" .
+	                    "Sec-WebSocket-Accept: $accept_key\r\n\r\n";
+
+		echo "[".date('Y-m-d H:i:s')."] Sending handshake)\n";
+		sendMesageToYou ($socket, $upgrade, true);
+	    return true;
+	}
+	else {
+	    return false;
+	}
+}
+
+function unmask($payload) {
+	$length = ord($payload[1]) & 127;
+
+	if($length == 126) {
+		$masks = substr($payload, 4, 4);
+		$data = substr($payload, 8);
+	}
+	elseif($length == 127) {
+		$masks = substr($payload, 10, 4);
+		$data = substr($payload, 14);
+	}
+	else {
+		$masks = substr($payload, 2, 4);
+		$data = substr($payload, 6);
+	}
+
+	$text = '';
+	for ($i = 0; $i < strlen($data); ++$i) {
+		$text .= $data[$i] ^ $masks[$i%4];
+	}
+	return $text;
+}
+
+function encode($text) {
+	// 0x1 text frame (FIN + opcode)
+	$b1 = 0x80 | (0x1 & 0x0f);
+	$length = strlen($text);
+
+	if($length <= 125) 		$header = pack('CC', $b1, $length); 	elseif($length > 125 && $length < 65536) 		$header = pack('CCS', $b1, 126, $length); 	elseif($length >= 65536)
+		$header = pack('CCN', $b1, 127, $length);
+
+	return $header.$text;
+}
+
+?>

file:b/server.php (new)
--- /dev/null
+++ b/server.php
@@ -1,1 +1,114 @@
+#!/usr/bin/php -q
+<?php
 
+set_time_limit(0);
+ob_implicit_flush();
+
+$dir = dirname(__FILE__);
+chdir ($dir);
+$root     = $dir."/";
+
+require ($root."server.functions.php");
+
+$address = '192.168.0.2';
+$port = 10001;
+
+$_sockets = array();
+
+if (($master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
+	echo "socket_create() failed, reason: " . socket_strerror($master) . "\n";
+}
+
+socket_set_option ($master, SOL_SOCKET, SO_REUSEADDR, 1);
+
+if (($ret = socket_bind($master, $address, $port)) < 0) {
+	echo "socket_bind() failed, reason: " . socket_strerror($ret) . "\n";
+}
+
+if (($ret = socket_listen ($master, 5)) < 0) {
+	echo "socket_listen() failed, reason: " . socket_strerror($ret) . "\n";
+} else {
+	$started=time();
+	echo "[".date('Y-m-d H:i:s')."] SERVER CREATED ( MAXCONN:".SOMAXCONN." ) \n";
+	echo "[".date('Y-m-d H:i:s')."] Listening on ".$address.":".$port."\n";
+}
+
+$read_sockets = array ($master);
+
+while (true) {
+	$changed_sockets = $read_sockets;
+	$num_changed_sockets = socket_select($changed_sockets, $write = NULL, $except = NULL, NULL);
+
+	foreach($changed_sockets as $socket) {
+	    if ($socket == $master) {
+			if (($client = socket_accept($master)) < 0) {
+				echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
+				continue;
+			} else {
+				array_push ($read_sockets, $client);
+				echo "[".date('Y-m-d H:i:s')."] CONNECTED "."(".count($read_sockets)."/".SOMAXCONN.")\n";
+			}
+		} else {
+			$bytes = @socket_recv ($socket, $buffer, 2048, 0);
+
+			if (strlen($buffer) == 0) {
+				//we get the user's unique id from the database
+				$id = $_sockets[intval($socket)]['session'];
+
+				$index = array_search ($socket, $read_sockets);
+
+				unset ($read_sockets[$index]); // we clean up
+				unset ($_sockets[intval($socket)]); // we clean up our own data
+				// cleaning up is essential when creating a daemon
+				// we can't leave junk in the memory
+				@socket_shutdown ($socket, 2);
+				@socket_close ($socket);
+			} else {
+				$allclients = $read_sockets;
+				array_shift ($allclients);
+
+				if ( !$_sockets[intval($socket)]['handshake'] ) {
+					$_sockets[intval($socket)]['handshake'] = true;
+					dohandshake($socket, $buffer);
+				}
+
+				$buffer = unmask($buffer);
+				//echo "[".date('Y-m-d H:i:s')."] BUFFER ".$buffer."\n";
+				$piece = explode("|",trim($buffer)); // we strip out all unwanted data
+				$cmd = strtolower ($piece[0]);
+
+				if ( !empty($piece[1]) ) {
+					$txt = $piece[1];
+				}
+
+				echo "[".date('Y-m-d H:i:s')."] Received ".$cmd." ".$txt."\n";
+
+				switch ($cmd) {
+					case "chat": // chat|session:message
+						$txt = explode (":", $txt);
+						$session = $txt[0];
+						$message = $txt[1];
+						//if ( $_sockets[intval($socket)]['session'] == $session ) {
+							//sendMesageToYou ($socket, $message);
+							sendMessageToAll ($allclients, $session, $message);
+						//}
+					break;
+
+					case "login"; // login|session
+						$txt = explode (":", $txt);
+						$session = $txt[0];
+
+						$_sockets[intval($socket)]['session'] = $session;
+						sendMesageToYou ($socket, "true aaa bbb");
+					break;
+
+					case "ping":
+						sendMesageToYou ($socket, "PONG");
+					break;
+				}
+			}
+		}
+	}
+}
+
+?>

comments