From CSE330 Wiki
Revision as of 03:02, 8 April 2013 by Shane (talk | contribs)
Jump to: navigation, search

A First Socket.IO Application: Chat Server and Client

Building a chat client is surprising simple using Socket.IO and Node.JS. We can do it in fewer than 5 minutes!

The Chat Server

You can make a file called chat.js with the following code:

// Require the packages we will use:
var http = require("http"),
	io = require(""),
	fs = require("fs");

// Listen for HTTP connections:
var app = http.createServer(function(req, resp){
	// This callback runs when a new connection is made to our HTTP server.
	fs.readFile("chat.html", function(err, data){
		// This callback runs when the chat.html file has been read from the filesystem.
		if(err) return resp.writeHead(500);

// Do the Socket.IO magic:
io.listen(app).sockets.on("connection", function(socket){
	// This callback runs when a new Socket.IO connection is established.
	socket.on("message", function(content){
		// This callback runs when the client sends us a "message" event
		console.log("message: "+content); // log it to the Node.JS output
		socket.broadcast.emit("someonesaid", content); // broadcast the message to other users

The above code makes a simple HTTP server that responds to all connections with the contents of the file "chat.html", which we will make in the next step. We tell Socket.IO to listen for "message" events, and when it hears one, it should emit a new event called "someone said" back to the connected clients.

The Chat Client

Here is a front-end client that could work with our server, in `chat.html`:

<!DOCTYPE html>
<title>Chat Client</title>

<!-- Include the Socket.IO and Ext libraries -->
<script src="/"></script>
<script src="//"></script>

<!-- Write our custom code -->
Ext.DomHelper.useDom = true; // prevent XSS

var socket = io.connect("http://localhost");
socket.on("someonesaid", function(content){
	// This callback runs when the server sends us a "someonesaid" event"messages").createChild({
		tag: "li",
		children: [content]
Ext.onReady(function(){"send").on("click", function(){
		// When the "send" button is clicked, emit a "message" event to the server containing a chat message
<ul id="messages">

	<textarea id="comment"></textarea>
	<button id="send">Send Comment</button>

Note: This example passes strings as the event data, but you can pass any JavaScript datatype, including object literals.

To see this in action, save these two files in the same directory, cd over to the directory, and start the server:

$ node chat.js

Fire up your favorite browser and navigate to http://localhost:3456/. Open the page in two windows. Violà: you have your (very basic) chat client!