Based on the first implementation of WebSockets in PHP, here comes a Web Chat with a little twist.
It uses little monsters as avatars thanks to gravatar and monster_id.
Get the code from the download zone!
Again, as of Feb/10 the only browsers that support websockets are Google Chrome and Safari nightlies.
var host = "ws://localhost:12345/phpwebsocketchat/chatserver.php";
try{
socket = new WebSocket(host);
socket.onopen = function(evt){ welcome(); };
socket.onmessage = function(evt){ process(evt.data); };
socket.onclose = function(evt){ goodbye(); };
}
catch(ex){ log(ex); }
View source code of chatclient.php
log("Handshaking...");
list($resource,$host,$origin) = getheaders($buffer);
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: WebSocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: " . $origin . "\r\n" .
"WebSocket-Location: ws://" . $host . $resource . "\r\n" .
"\r\n";
$handshake = true;
socket_write($socket,$upgrade.chr(0),strlen($upgrade.chr(0)));
View source code of chatserver.php
- Download all files to a folder in your local server running Apache and PHP.
- From the command line, run the chatserver.php program to listen for socket connections.
- Open Google Chrome and point to the chatclient.php page
- Done, your browser now has a full-duplex channel with the server.
- Start chatting with your friends in real time!
George Nava