HelloWorld in Node.js Using Socket.IO

1. If you have not already done so, download and install Node.js. Make a note of the directory to which node.exe is installed.

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

3. Open a command prompt and enter “npm install socket.io”. The socket.io package for Node.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 “NodeSocketIOTest”.

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

var portToListenOn = 8089;
var io = require('socket.io').listen(portToListenOn);

io.sockets.on
(
	'connection', 
	function (socket) 
	{
		socket.emit("connectionSuccessful");
		socket.on
		(
			'messageFromClientToServer', 
			function (data) 
			{
				console.log("Message Received from Client:" + data);
			}
		);
	}
);

6. Still in the NodeSocketIOTest 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'>

	var connectionToServer = io.connect("http://localhost:8089");
	connectionToServer.on
	(
		'connectionSuccessful', 
		function(data) 
		{
			alert("Connection successful!");
			connectionToServer.emit
			(
				"messageFromClientToServer",
				"Hello, Server.  It's me, Client."
			);
		}
	);

</script>

</body>
</html>

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

node Server.js
pause

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

9. Open Client.html in a web browser that runs JavaScript and wait a few moments. A dialog will appear that says “Connection Successful!”, and a message that reads “Hello, Server. It’s me, Client.” will appear in the console window for Server.js.

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