HTML5 WebSockets Example

HTML5 WebSockets makes it possible to open a persistent connection to a server within a web-browser via javascript.

UPDATE: Mastering the new Spec-76 WebSockets handshake with PHP.

Websockets works already in the latest Webkit-browsers like Safari 5 and Chrome 5. Firefox 4 Beta 1 knows the Websocket-Object but it can’t open the connection :(

My Websocket test script sends the current mouse position via socket connection to the server and then receives all positions of all current open sockets and prints them to the browser-window. In other words, you can see the mouse cursors of the other users on the page.

var socket;
 
function init() {
	var host = "ws://84.38.67.247:8080/dev/websocket/server.php";
	try {
		socket = new WebSocket(host);
		socket.onopen = function(msg){ };
		socket.onmessage = function(msg){
			eval('var data = ' + msg.data + ';');
			for (userId in data) {
				if (data[userId].position) {
					var pos = data[userId].position.split(',');
					var color = data[userId].color;
					render(userId, pos[0], pos[1], color);
				}
			}
			dump(data);
		};
		socket.onclose = function(msg){ };
	} catch(ex){ console.log(ex); }
 
	$('body').bind('mousemove', function(evt){
		send(evt.clientX, evt.clientY);
	});
}
 
function render(u, x, y, c) {
	if ($('#'+u).length == 0) {
		$('
 
').appendTo('body');
	}
	$('#'+u).css('left', x+'px');
	$('#'+u).css('top', y+'px');
	$('#'+u).css('background', c);
}
 
function send(x,y) {
	var msg = x + ',' + y;
	socket.send(msg);
}

On the server side i use a PHP5 script. I have written my own server-class but it’s based on the work of the phpwebsocket project. The server.php instantiate the WebSocketServer object and contains the callback function.

New URL for Example: http://bohuco.net/labs/php-websocket-class/

http://bohuco.net/dev/websocket/

Source Codes:
WebSocketServer.php
server.php