Logo  

CS479/579 - Web Programming II

Web-sockets:

A websocket creates a bi-directional, persistent connection to a server (e.g. one created in node.js) that supports web-socket communication.

On the client (in ECMAScript):

var sock = new WebSocket("ws://host:port/", optional-protocol);

  • Creates a new web-socket object to the given ws:// or wss:// url to a remote host and port. The optional-protocol is a single protocol string or array of protocol strings that may influence the behavior of the handling of the web-socket by the remote server.

example: ws://cs.indstate.edu:60000/

  • Use wss for SSL secured socket connections.

Methods

.send(data);

  • send data to the server. Data may be a string, Blob, or ArrayBuffer.

.close();

  • closes the connection.

Event handlers:

.onopen = function(event) { ... }

  • Fired when the connection is finalized. It is not possible to send data until the connection is finalized. Once this callback is called it is safe to send data to the server.

.onmessage = function(mesg) { ... }

  • Sets up a listener callback for when we receive data on the socket. Received data is in mesg.data.

.onerror = function(event) { ... }

  • Called when an error on the socket occurs.

.onclose = function(event) { ... }

  • Called when the web-socket is closed.

server.js

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.

chat.html

<!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>