This is a very simple single-room chat client using node.js, socket.io and the express module.
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
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
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?
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.
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.
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.
its a gr8 example :) :) any pointers towards how to deploy such code on a dedicated server …
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).
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
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.
Want to put this app in a github repo so we can talk about it & fix it there?
Sure, I was thinking about it. I’ll do it tonight.
Sweet!
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
youre using putty to connect to a remote server? are you loading the remote server in your browser?
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
Problem fixed ;-) IT WORKS!!!!
hey, manto has a question for you in the comment below. thanks :)
Truelli: What did you change to make it work? I am currently seeing the same problem you are seeing.
Worked perfect man, thank you so much for this. I have been looking for exactly this to try and learn.
awesome! thanks
Thanks for this awesome tutorial, I loved it! Hope to see more!
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.
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.
Haha, glad to see it worked. Let me know if you have any other issues.
Great concise tutorial, this was exactly what I was looking for. Thanks!
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!!!
update … it works, but not on chrome or firefox, am I missing something?
Thanks!!!
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.
Thank you, this is a great tutorial, I was able to finally create a clean installation and working demo.
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?
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.
Thanks for the example
do the webserver’s port and socket listen port are neccessarily same??
Good question, I’m guessing no. You can quickly test :)
it works on different method.. :)
when i invoke io.socket.emit(“someMethod”) [client method] is called twice when i see the console..Any reason??..how this io.socket.emit works
IIRC, broadcast() sends messages to everyone besides the client, while emit() sends to everyone including yourself. I have a short explanation in the 2nd tut (http://psitsmike.com/2011/10/node-js-and-socket-io-multiroom-chat-tutorial/)
sorry it works on different port.. :)
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.
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..
How many users do you think this set up can handle before the server gets noticeably bogged down?
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.
This tutorial extends nicely on the one found in ‘Node: Up & Running’.
Exactly what I was looking for, cheers.
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.
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!
gracias…me ha servido de mucho
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??
forget what I said, it works
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.
Thanks Mike! I put up a working example here:
https://github.com/dirkk0/minimalchat
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
If anyone is getting path join errors, see updated version for express 3.x at: https://github.com/nicangeli/nodechat/
this saved me thank you so much!
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
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)
res.sendfile( ‘/index.html’ , {root:__dirname});
any more functionality on this
so far works great I want to build a mpg with chat
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)
Thanks for this tutorial, it is easy to undestant for staring nodejs
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.
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.
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.
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
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.!
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
helpful, very helpful
thank you
Is this a “tutorial”?
Or, here is the code, it works and rest you will understand yourself :@
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
Hi Michael
I was just sorting the user to user chat I mean chat between the two online persons privately.
Although your article is fantastic and I have done with the basic.
In above someone has asked for the same thing as I am asking, you replied you will share a link tutorial for person to person chat room.
I have found no link above.
Can you post this link.
I will be very thankful for your help.
I don’t have the link, but you could create a new “chatroom” for two people who want to chat.. you can title it “jim_bob_private” and don’t list is as available for others.
I am getting below error though msg can be sent but clinet is getting disconneted now and then…
application is deployed on linux server.
there are no such error when we run it on https… but i cant use use https
WebSocket connection to ‘ws://test.com/socket.io/?EIO=3&transport=websocket&sid=KM5SZWyyC5e2Omq7AAAH’ failed: Establishing a tunnel via proxy server failed.
socket.io.js:2919 GET http://test.com/socket.io/?EIO=3&transport=polling&t=1436865165474-226&sid=OUB_PN–PYgvLCq1AAAD 503 (Service Unavailable)17.Request.create @ socket.io.js:2919Request @ socket.io.js:284217.XHR.request @ socket.io.js:277317.XHR.doPoll @ socket.io.js:280318.Polling.poll @ socket.io.js:319218.Polling.onData @ socket.io.js:3231(anonymous function) @ socket.io.js:28069.Emitter.emit @ socket.io.js:133517.Request.onData @ socket.io.js:295417.Request.onLoad @ socket.io.js:302517.Request.create.xhr.onreadystatechange @ socket.io.js:2907
Please help me in this…