Socket.IO
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("socket.io"),
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);
resp.writeHead(200);
resp.end(data);
});
});
app.listen(3456);
// 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>
<html>
<head>
<title>Chat Client</title>
<!-- Include the Socket.IO and Ext libraries -->
<script src="/socket.io/socket.io.js"></script>
<script src="//cdn.sencha.io/ext-4.1.1-gpl/ext-all-dev.js"></script>
<!-- Write our custom code -->
<script>
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
Ext.fly("messages").createChild({
tag: "li",
children: [content]
});
});
Ext.onReady(function(){
Ext.fly("send").on("click", function(){
// When the "send" button is clicked, emit a "message" event to the server containing a chat message
socket.emit("message", Ext.fly("comment").getValue());
});
});
</script>
</head>
<body>
<ul id="messages">
</ul>
<p>
<textarea id="comment"></textarea>
<button id="send">Send Comment</button>
</p>
</body>
</html>
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!