Difference between revisions of "Socket.IO"

From CSE330 Wiki
Jump to navigationJump to search
Line 90: Line 90:
 
Ext.DomHelper.useDom = true; // prevent XSS
 
Ext.DomHelper.useDom = true; // prevent XSS
  
var socket = io.connect("http://localhost");
+
var socket = io.connect();
 
socket.on("someonesaid", function(content){
 
socket.on("someonesaid", function(content){
 
// This callback runs when the server sends us a "someonesaid" event
 
// This callback runs when the server sends us a "someonesaid" event
Line 123: Line 123:
 
To see this in action, save these two files in the same directory, cd over to the directory, and start the server:
 
To see this in action, save these two files in the same directory, cd over to the directory, and start the server:
  
<source lang="bash">$ node chat.js</source>
+
<source lang="bash">$ node chat-server.js</source>
  
 
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!
 
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!

Revision as of 07:19, 17 November 2013

AJAX is useful when one-way communication is satisfactory for your web application. However, what happens when you need two-way communication, like a chat client or multiplayer game? AJAX isn't the tool for the job. This is where Socket.IO comes in.

Built to work natively with Node.JS, Socket.IO enables asynchronous, two-way communication between the server and the client. This means that the server can send messages to the client without the client having to ask first, as is the case with AJAX. As you learn Socket.IO, Non-Blocking I/O will become your best friend!

Installing Socket.IO

Before you install Socket.IO, you need to install Node.JS and NPM, which is often installed automatically when you install Node.JS.

The NPM package manager is different from many of the package managers we've used in that you need to install remote packages for every project in which you use them. This means that you need to cd to the working directory in which you want to keep your Node.JS JavaScript file, and then run the following command:

$ npm install socket.io

Note: If you pass the -g to npm install, then the package will be installed "globally" on your instance, so all Node.JS projects will be able to use it. However, this is not recommended for all projects. Read Node.JS's justification here.

Messaging

Socket.IO works by having clients send messages to the server and the server send messages to clients. For example, consider the code:

// Computer A:
socket.emit("info", {
	"hello": "world"
});

// Computer B:
socket.on("info", function (data) {
	console.log(data.hello);
});

Computer A could be either the client or the server, and Computer B would be the other. When socket.emit(name, data) is called on either end, the callback function in socket.on that listens for the message named name is called with the data from socket.emit.

A First Socket.IO Application: Chat Server and Client

Building a chat client is surprising simple using Socket.IO and Node.JS, and it gives great insight into the workings of Socket.IO. Take the time to understand how this example works, and ask questions; if you understand this, the group portion will be easy!

The Chat Server

You can make a file called chat-server.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.  This is essentially a miniature static file server that only serves our one file, chat.html:
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();
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-server.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!

Resources

The Socket.IO web site has concise examples that tell you pretty much all you need to know in order to build a functional Socket.IO web application.