Skip to content

node.js and socket.io chat tutorial

i found that the ready availability of documentation and the eagerness of experienced individuals to help the newly adopting, throughout the node.js communities, allow for quicker learning and sharing of acquired skills

i’ve created a very simple single-room chat client using node.js, socket.io and the express module

UPDATE: long overdue, but you can now skip the following step and just install via the .msi or .pkg files and they include NPM – http://nodejs.org/#download

to begin, you must install node.js and npm along with their dependencies

cd /pick_a_folder
git clone git://github.com/joyent/node.git
cd node
git checkout v0.4.12  #or latest stable version
./configure
make
make install #finish nodejs install
curl http://npmjs.org/install.sh | sh #install npm

ok! you’ve installed node, npm, and are ready to start coding. to make development much easier, let’s install the express and socket.io modules through the npm. create a directory that you’d like this project to be housed in (e.g. mkdir /home/chat). create a file titled package.json

{
     "name": "mukhin_chat",
     "description": "example chat application with socket.io",
     "version": "0.0.1",
     "dependencies": {
        "express": "2.4.6",
        "socket.io": "0.8.4"
     }
}

now, install the modules

npm install -d

let’s now create the server file, app.js

var app = require('express').createServer()
var io = require('socket.io').listen(app);

app.listen(8080);

// routing
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

// usernames which are currently connected to the chat
var usernames = {};

io.sockets.on('connection', function (socket) {

	// when the client emits 'sendchat', this listens and executes
	socket.on('sendchat', function (data) {
		// we tell the client to execute 'updatechat' with 2 parameters
		io.sockets.emit('updatechat', socket.username, data);
	});

	// when the client emits 'adduser', this listens and executes
	socket.on('adduser', function(username){
		// we store the username in the socket session for this client
		socket.username = username;
		// add the client's username to the global list
		usernames[username] = username;
		// echo to client they've connected
		socket.emit('updatechat', 'SERVER', 'you have connected');
		// echo globally (all clients) that a person has connected
		socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
		// update the list of users in chat, client-side
		io.sockets.emit('updateusers', usernames);
	});

	// when the user disconnects.. perform this
	socket.on('disconnect', function(){
		// remove the username from global usernames list
		delete usernames[socket.username];
		// update list of users in chat, client-side
		io.sockets.emit('updateusers', usernames);
		// echo globally that this client has left
		socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
	});
});

now, let’s create the client file, index.html

<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
	var socket = io.connect('http://localhost:8080');

	// on connection to server, ask for user's name with an anonymous callback
	socket.on('connect', function(){
		// call the server-side function 'adduser' and send one parameter (value of prompt)
		socket.emit('adduser', prompt("What's your name?"));
	});

	// listener, whenever the server emits 'updatechat', this updates the chat body
	socket.on('updatechat', function (username, data) {
		$('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
	});

	// listener, whenever the server emits 'updateusers', this updates the username list
	socket.on('updateusers', function(data) {
		$('#users').empty();
		$.each(data, function(key, value) {
			$('#users').append('<div>' + key + '</div>');
		});
	});

	// on load of page
	$(function(){
		// when the client clicks SEND
		$('#datasend').click( function() {
			var message = $('#data').val();
			$('#data').val('');
			// tell server to execute 'sendchat' and send along one parameter
			socket.emit('sendchat', message);
		});

		// when the client hits ENTER on their keyboard
		$('#data').keypress(function(e) {
			if(e.which == 13) {
				$(this).blur();
				$('#datasend').focus().click();
			}
		});
	});

</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
	<b>USERS</b>
	<div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
	<div id="conversation"></div>
	<input id="data" style="width:200px;" />
	<input type="button" id="datasend" value="send" />
</div>

run the server

node app.js

load up http://localhost:8080 in your browser

GIT repo https://github.com/mmukhin/psitsmike_example_1

UPDATE: i’ve written up a multiroom chat tutorial here

Comment Feed

74 Responses

  1. Hi. Thanks for great and yet simple tutorial. I’ve problem this running on any browser (Windows 7) except IE9. Node server is running on Linux of course. Is it a problem with Socket.IO, do you know anything about that?

    • michael mukhinOctober 8, 2011 @ 10:36 amReply

      So you have 2 different computers and one is running linux, one is running w7? I’ve tested on W7, OS X and Ubuntu (firefox + chrome) and it worked for me. Have not tested in IE yet. I’ll try it and get back to you.

    • YourbuttButtmunchApril 29, 2012 @ 9:32 pmReply

      If you’re in windows, go to the Command Prompt. Go to the directory you’re placing the APP in. Type “npm -install socket.io” and wait. When it’s done, go into the node_modules directory. Cut everything out of there and bring it back into your app folder. Put your app.js file and all the files from this tutorial there. I can’t vouch for this tutorial yet. It may have path bugs.

      • michael mukhinApril 30, 2012 @ 9:48 amReply

        So I tested on windows7 initially. It should work, should be platform independent. Let me know if there are bugs, I’ll definitely update. Thanks Buttmunch.

  2. its a gr8 example :) :) any pointers towards how to deploy such code on a dedicated server …

    • michael mukhinOctober 13, 2011 @ 7:30 pmReply

      Sure, all you need to change is the index.html io.connect url from http://localhost:8080 to http://yourdomain.com:8080 (or whatever port you prefer, make sure to use the same port in the app.js file).

      But to run this, you need node installed on the server (i have a linux vps).. if you cant do that, google for free node.js hosting (i think no.de offers something like that).

  3. Hi, I tried runnning this code on my linux machine (except using express 2.4.7 and socket.io 0.8.5, both changes reflected in my package.json, although i did try it with your exact package.json file and it still didn’t work)

    The server starts up and can be viewed, however no prompt is asked for username, and upon posting a message, the only thing that occurs is the clearing of the data field…

    Please help me understand what problem is occuring, I will provide any additional information as required

    • michael mukhinOctober 16, 2011 @ 2:17 pmReply

      When you run the app using “node app.js”, do you get any errors in your terminal? The following should show up immediately:
      info – socket.io started

      • Thank you for the response. It was giving that “info – socket.io started”, however I was accessing the site from another computer on the network, but the code only serves the socket information to localhost, which I did not understand. I have added my ip and port to the client side code and it is working across the network now. Thank you for your time.

  4. Want to put this app in a github repo so we can talk about it & fix it there?

  5. Hi, great script… but something is wrong. the app.js said “info . socket.io startet

    at the Client side I type my name left from the send-button and clicked it, but nothing… no reaction in putty or browser…

    I try Chrome 15 and safari 5.1
    can you help me pls?
    Truelli

    • michael mukhinOctober 26, 2011 @ 9:36 pmReply

      youre using putty to connect to a remote server? are you loading the remote server in your browser?

  6. Yes, I am using putty to connect to my webserver via SSH and yes… I try to load this server via browser-session to run the chat-script for my users. I changed the localhost:port to the server-IP-Address:port

  7. Problem fixed ;-) IT WORKS!!!!

  8. Truelli: What did you change to make it work? I am currently seeing the same problem you are seeing.

  9. Worked perfect man, thank you so much for this. I have been looking for exactly this to try and learn.

  10. Thanks for this awesome tutorial, I loved it! Hope to see more!

  11. Tim HopeMarch 17, 2012 @ 12:55 amReply

    New to node and socket.io, this was a brilliant help, thank you.

    Only trouble is when I visit the page in chrome it freezes. The first time I ran it, it worked asked me my name, but it didn’t update on the list, made some changes to the code and visited the page again, it didn’t ask my name it just froze Chrome and the server kept ticking away with something about stopping client timeouts.

    Is there some sort of session sticking around that I may have missed? I’ve closed and reopened chrome checked for any cookies associated with the page.

    Any help would be greatly appreciated.

    • Tim HopeMarch 17, 2012 @ 1:02 amReply

      Boy do I feel intelligent… it was just the dialogue box disagreeing with my “Keep Window on Top” tool.

      Yep…

      It’s working brilliantly! Thank you so much.

  12. Great concise tutorial, this was exactly what I was looking for. Thanks!

  13. Thanks for this tutorial … however, I can’t make it run.

    here is my node console after connecting with chrome and firefox

    C:\Users\shlomis>node C:\dev\wamp\www\chat\app.js
    info – socket.io started
    debug – served static content /socket.io.js
    debug – client authorized
    info – handshake authorized 17328410771834238112
    debug – setting request GET /socket.io/1/websocket/17328410771834238112
    debug – set heartbeat interval for client 17328410771834238112
    debug – client authorized for
    debug – websocket writing 1::
    debug – served static content /socket.io.js
    debug – client authorized
    info – handshake authorized 201653512237575438
    debug – setting request GET /socket.io/1/websocket/201653512237575438
    debug – set heartbeat interval for client 201653512237575438
    debug – client authorized for
    debug – websocket writing 1::
    debug – setting request GET /socket.io/1/xhr-polling/17328410771834238112?t=1
    333974550605
    debug – setting poll timeout
    debug – discarding transport
    debug – cleared heartbeat interval for client 17328410771834238112
    debug – setting request GET /socket.io/1/xhr-polling/201653512237575438?t=133
    3974554686
    debug – setting poll timeout
    debug – discarding transport
    debug – cleared heartbeat interval for client 201653512237575438

    I see the index.html file but can’t send any message … any idea?

    Thanks!!!

  14. update … it works, but not on chrome or firefox, am I missing something?

    Thanks!!!

    • michael mukhinApril 10, 2012 @ 7:17 amReply

      I think other people had a problem on windows, but got it fixed. Odd because latest versions of chrome/ffx support websockets. I’ll try and see.

  15. Thank you, this is a great tutorial, I was able to finally create a clean installation and working demo.

  16. Thanks for this great tutorial… i just want to know how can i make this a user-to-user chat?
    I mean, a user must be able to select another user and send him a private message. Is it possible?

    • michael mukhinApril 21, 2012 @ 12:36 pmReply

      Well you’re going to have to set up a “personal room” only accessible to those 2 people (socket.io provides this). You could have an “onclick” event when clicking on somebody’s username that creates a new room. Then only broadcast messages there. I have another tutorial that makes multi-user chatrooms. Let me know if that makes sense.

  17. Thanks for the example

  18. do the webserver’s port and socket listen port are neccessarily same??

  19. Great Tutorial. Was able to get it up and running and I had no real experience with node or socket.io.

    I have issues on mobile devices though: When I have poor connection I start to get multiple copies of responses along with multiple “has connected” messages.
    It’s as if it connects multiple times and the server thinks the device is multiple users and send a response to each.

    • michael mukhinMay 4, 2012 @ 9:24 amReply

      You’d want to listen on any ‘disconnect’ for all sockets and kick those people out of the room. I haven’t re-visited the tutorial in a while ;)

      • It looks more like the client is connecting multiple times before server knocks them off.
        The problem is on an android device (have not tested ios yet) so I assume its using flash or ajax.
        Not sure how the handshaking works for each method but perhaps a check on the server side to not do ‘adduser’ if user is already in list? Will give it a try..

  20. How many users do you think this set up can handle before the server gets noticeably bogged down?

    • michael mukhinMay 4, 2012 @ 9:22 amReply

      I don’t yet have any experience under real stress. Of course depends on your server, but im guessing no issues from 100-1k? I remember reading Trello turns off all options besides WebSockets (i.e. turn off ajax, flash, etc) and it works great for them.

      • Android is big for me so I can’t rely on websockets alone but a few hundred should be cool for the near term. Thanks.

  21. This tutorial extends nicely on the one found in ‘Node: Up & Running’.

    Exactly what I was looking for, cheers.

  22. Shekhar SumanJuly 4, 2012 @ 8:59 pmReply

    I have a problem. When I try to run it on Chrome or Firefox, there is no prompt for entering a username. However it works perfectly on IE.
    Also when I open them separately on IE and chrome and send the messages from IE, I can receive them on chrome.

  23. Shekhar SumanJuly 4, 2012 @ 9:07 pmReply

    There is one more thing. When I try to run it on chrome, I get a prompt only when I stop the server by pressing ctrl+c. Please help!

  24. gracias…me ha servido de mucho

  25. Hi, i’m a noob.

    When i start app.js the console shows me some problems.
    First:
    “Warning: express.createServer() is deprecated, express application no longer inherit from http.Server”

    Second:
    “Socket.IO’s ‘listen()’ method expects an ‘http.Server’ instance as its first parameter. ”

    Some suggestions??

  26. Hi Michael ,

    Nice tutorial.

    if you replace

    io.sockets.emit(‘updatechat’,socket.username, data);

    with

    if(socket.username){ io.sockets.emit(‘updatechat’,socket.username, data);
    }

    It removes null message at the begining.

  27. Thanks Mike! I put up a working example here:
    https://github.com/dirkk0/minimalchat

  28. Hi Mike ,

    thanks for the tutorial , its pretty simple and nicely explained. Just want to say thanks. It executed perfect without any issues for me

  29. If anyone is getting path join errors, see updated version for express 3.x at: https://github.com/nicangeli/nodechat/

  30. i have a problem in Node.js

    NetworkError: 500 Internal Server Error – http://127.0.0.1:8080/

    anybody know how to fix this?

    Thanks

  31. TypeError: Arguments to path.join must be strings
    at f (path.js:204:15)
    at Object.filter (native)
    at exports.join (path.js:209:40)
    at exports.send (C:\Users\Maloy\node_modules\express\node_modules\connect\lib\middleware\static.js:129:20)
    at ServerResponse.res.sendfile (C:\Users\Maloy\node_modules\express\lib\response.js:186:3)
    at usernames (C:\Users\Maloy\app.js:8:7)
    at callbacks (C:\Users\Maloy\node_modules\express\lib\router\index.js:272:11)
    at param (C:\Users\Maloy\node_modules\express\lib\router\index.js:246:11)
    at pass (C:\Users\Maloy\node_modules\express\lib\router\index.js:253:5)
    at Router._dispatch (C:\Users\Maloy\node_modules\express\lib\router\index.js:280:5)

  32. any more functionality on this
    so far works great I want to build a mpg with chat

  33. hi,
    it does not work it give me these error in the browser:
    TypeError: Arguments to path.join must be strings
    at path.js:360:15
    at Array.filter (native)
    at exports.join (path.js:358:36)

  34. Thanks for this tutorial, it is easy to undestant for staring nodejs

  35. Working great. I had to install socket.io expres
    After that its working awesome.
    One question, may i use node.js on shared hosting or need dedicated server.
    Please help.
    Thanks in advance.

  36. I have tried this and I’m running into the following errors. At first when I tried to run the node app.js it told me it couldn’t find express module, so I downloaded the package for express and now I am running into the following error:
    Warning: express.createServer() is depreicated, express applications no longer inherit from http.Server, please use: var express = require(“express”); var app = express();

    Any help would be greatly appreciated.

  37. Perfect script!
    Used it as base to develop a (more) complex chat app integrated to an intranet. Works fine!
    Gonna push it to github when done.

  38. There is no answer on google to “how do we make this thing live”. I can run it locally but what if i have to use it in my android application? i have dedicated server of my own. How to use that for this socket.io. it requires me to run node server. but that is for local network

  39. Gre8 tutorial. Could you please give me pointers on how to build this using sessions. Basically I want the username to the stored in the browser.!

  40. hii sir i am new to node js whenever i write something in messenger i only got it in URL what i am doing wrong plzzz help

  41. helpful, very helpful
    thank you

  42. Is this a “tutorial”?
    Or, here is the code, it works and rest you will understand yourself :@

  43. Check this interactive course that gives you all the keys to a good start of node.js, Express.js and socket.io by taking all the power of it.
    This course is regularly updated.
    https://www.udemy.com/nodejs-tutorial-from-scratch-by-examples



Some HTML is OK

or, reply to this post via trackback.

CAPTCHA Image
*

Continuing the Discussion

  1. [...] cd /pick_a_folder git clone git://github.com/joyent/node.git cd node git checkout v0.4.12 #or latest stable version ./configure make make install #finish nodejs install curl http://npmjs.org/install.sh | sh #install npm ok! you’ve installed node, npm, and are ready to start coding. to make development much easier, let’s install the express and socket.io modules through the npm. create a directory that you’d like this project to be housed in (e.g. mkdir /home/chat). create a file titled package.json to begin, you must install node.js and npm along with their dependencies node.js and socket.io chat tutorial – ps: it's mike [...]

  2. [...] also need an example app that uses Socket.io. Michael Mukhin has an easy, ready to go chat app tutorial that we’ll be making use of. Be sure to get the latest code from his github repository. You [...]

  3. [...] + gevent + Flask + nginx > Dweez > Développement node.js and socket.io chat tutorial – michael mukhin i found that the ready availability of documentation and the eagerness of experienced individuals [...]

  4. [...] If you got to this point and everything went ok, you’re ready to test the whole stack we’ve insatlled so far. Let’s create a simple node.js chat application (adapted from here): [...]

  5. [...] -http://psitsmike.com/2011/09/node-js-and-socket-io-chat-tutorial/-https://github.com/LearnBoost/Socket.IO-node-https://github.com/Automattic/socket.io-http://howtonode.org/websockets-socketio-http://stackoverflow.com/questions/4094350/good-beginners-tutorial-to-socket-io-http://danielnill.com/nodejs-tutorial-with-socketio/-http://sideeffect.kr:8005/-http://vijayannadi.wordpress.com/tutorials/sample-chat-app-using-nodejs-socketio/-http://javaguirre.net/2014/02/11/twitter-streaming-api-with-node-socket-io-and-reactjs/ [...]