A websocket creates a bi-directional, persistent connection to a server (e.g. one created in node.js) that supports web-socket communication.
var sock = new WebSocket("ws://host:port/", optional-protocol);
var sock = new WebSocket("ws://
:
/",
);
ws://
wss://
example: ws://cs.indstate.edu:60000/
ws://cs.indstate.edu:60000/
wss
.send(data);
.send(
.close();
.onopen = function(event) { ... }
.onmessage = function(mesg) { ... }
mesg.data
.onerror = function(event) { ... }
.onclose = function(event) { ... }
The following is a broadcast server for node.js. It broadcasts any received message to all connected clients (even back to the sender.)
var WebSocketServer = require("/usr/local/lib/node_modules/ws").Server; var wsserver = new WebSocketServer({port:60000}); wsserver.on("connection", function(client) { client.on("message", function(message) { console.log("Message: %s", message); for(var i in wsserver.clients) { wsserver.clients[i].send(message); } }); client.send(JSON.stringify({name: "", message: "Connected!"})); });
wsserver is the web socket server object. A connection event is bound with a function that is passed client a new web socket client object. It then bind to the web socket client it's message event a function that broadcasts the received message to all clients connected to the server. The server also sends a connection message to the client that just connected.
wsserver
client
<!DOCTYPE html> <html> <head> <title> </title> <meta charset='utf-8'> <style> #chatwin { min-width: 90%; } #chatlog { border: 1px solid black; overflow-y: scroll; height: 480px; } input[type=text] { min-width: 100%; border: 1px solid gray; font-size: 20pt; border-radius: 4px; } </style> <script> // The users saved name and the connection object: var _name = null, _conn = null; /** * Called after a name is entered. Establishes the web-socket connection and * setups the onmessage event listener which adds received messages to the * chatwin. */ function setup(e) { console.log("setup: %s", e.value); _name = e.value; e.value = ""; document.getElementById("name").setAttribute("style", "display:none;"); document.getElementById("chatwin").setAttribute("style", "display:table;"); _conn = new WebSocket("ws://cs.indstate.edu:60000/", "test"); _conn.onmessage = function(em) { var data = JSON.parse(em.data); var l = document.getElementById("chatlog"); l.innerHTML += "<strong>" + data.name + "</strong>: " + data.message + "\n"; } } function send(e) { _conn.send(JSON.stringify({name: _name, message: e.value})); e.value = ""; } </script> </head> <body> <!-- The chatwin table is not visible initially. The Name input is removed after a name is entered and the chatwin is made visible. --> <label id='name'> Name: <input type='text' onchange='setup(this);'></label> <table id='chatwin' style='display:none;'> <tr><td><pre id='chatlog'></pre></td></tr> <tr><td><input type='text' onchange='send(this);'></td></tr> </table> </body> </html>