A Client/Server System with IO.js and Socket.IO

The JavaScript code below implements a simple client-server system using IO.js. To see it in action, follow the steps below.

TimeServerAndClients

1. If you have not already done so, download and install IO.js (or, if preferred, its predecessor, Node.js). Make a note of the directory to which iojs.exe is installed.

2. Make sure that the directory containing iojs.exe is present in the “Path” environment variable.

3. Open a command prompt and enter “npm install socket.io”. The Socket.IO package for IO.js will be installed. (Note that if these files are ever moved to a different directory, it may be necessary to run this command again in the destination directory. Supposedly there is a way to install the package globally, but it does not seem to work in all cases.)

4. In any convenient location, create a new directory named “SocketIOClientServerTest”.

5. In the newly created SocketIOClientServerTest directory, create a new text file named “Server.js”, containing the following text.

function Server(portToListenOn)
{
	this.portToListenOn = portToListenOn;
	this.socketsToClients = [];
}
{
	Server.prototype.sendMessageToClient = function(messageText, clientIndex)
	{
		var socketToClient = this.socketsToClients[clientIndex];
		console.log("Server: " + messageText);
		socketToClient.emit
		(
			"messageFromServerToClient",
			messageText	
		);				
	}

	Server.prototype.start = function()
	{
		var socketIO = require("socket.io");
		var io = socketIO.listen
		(
			this.portToListenOn,
			{ log: false }
		);

		io.sockets.on
		(
			"connection", 
			this.handleEventConnection.bind(this)
		);

		console.log("Time server started at " + new Date().toLocaleString());
		console.log("Listening on port " + this.portToListenOn + "...");
	}

	// events

	Server.prototype.handleEventConnection = function(socketToClient)
	{	
		var clientIndex = this.socketsToClients.length;

		this.socketsToClients.push(socketToClient);

		var messageToClient = 
			"Hello. You are client number " + clientIndex + ".";

		console.log("Server:", messageToClient);

		socketToClient.emit
		(
			"connectionSuccessful", 
			messageToClient
		);

		socketToClient.on
		(
			"messageFromClientToServer", 
			this.handleEventMessageFromClientToServer.bind
			(
				this, clientIndex
			)
		);
	}

	Server.prototype.handleEventMessageFromClientToServer = function(clientIndex, data)
	{
		console.log("Client" + clientIndex +  ": " + data);
		var now = new Date();
		var timeAsString = now.toLocaleTimeString();
		var messageText = "The time is " + timeAsString + ", Client " + clientIndex + ".";
		this.sendMessageToClient(messageText, clientIndex);
	}
}

new Server(8089).start();

6. Still in the SocketIOClientServerTest directory, create a new text file named “Client.html”, containing the following text.

<html>
<body>

<script type="text/javascript" src="http://localhost:8089/socket.io/socket.io.js"></script>

<script type="text/javascript">

function Client(serviceURL)
{
	this.serviceURL = serviceURL;
}
{
	Client.prototype.randomIntervalBetween = function(min, max)
	{
		var range = max - min;
		var returnValue = min + Math.floor(Math.random() * range);
		return returnValue;
	}

	Client.prototype.sendMessageToServer = function(messageText)
	{
		this.writeLine("Client: " + messageText);
		this.connectionToServer.emit
		(
			"messageFromClientToServer",
			messageText	
		);
	}

	Client.prototype.start = function()
	{
		this.writeLine("Attempting to connect to " + this.serviceURL + "...");	

		this.connectionToServer = io.connect(this.serviceURL);
		this.connectionToServer.on
		(
			"connectionSuccessful", 
			this.handleEventConnectionSuccessful.bind(this)
		);

		this.connectionToServer.on
		(
			"messageFromServerToClient",
			this.handleEventMessageServerToClient.bind(this)
		);
	}

	Client.prototype.writeLine = function(text)
	{
		document.write(text);
		document.write(Constants.LineBreak);
	}

	// events

	Client.prototype.handleEventConnectionSuccessful = function(data)
	{
		this.handleEventMessageServerToClient(data);
	}

	Client.prototype.handleEventMessageServerToClient = function(data)
	{
		this.writeLine("Server: " + data);
		var messageText = "Hey, Server, what time is it?";
		setTimeout
		(
			this.sendMessageToServer.bind(this, messageText),
			this.randomIntervalBetween(2, 5) * Constants.MillisecondsPerSecond
		);
	}
}

function Constants()
{
	// static class
}
{
	Constants.LineBreak = "<br />";
	Constants.MillisecondsPerSecond = 1000;
}

new Client("http://localhost:8089").start();

</script>

</body>
</html>

7. Still in the SocketIOClientServerTest directory, create a new text file named “Server-Run.bat”, containing the following text.

iojs Server.js
pause

8. Execute Server-Run.bat. A console window will appear, within which status messages from the IO.js server can be viewed.

9. Open Client.html in a web browser that runs JavaScript. The client will establish a connection to the server, and messages will begin to be passed back and forth.

10. Open another copy of Client.html in a different browser window. This client will connect to the same server, and messages will begin to be passed between the server and this second client as well.

11. Watch the messages appearing in server’s console window and the two client web browsers for a while.

Advertisements
This entry was posted in Uncategorized and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s