Recently at the “Noser E-Days”, a company wide team meeting. We decided to build a little chat server with node.js and various chat client implementations with java script frameworks like angular.js. I got the task to write the chat server and was amazed on how easy it was to realize it with node.js.
Following the steps I needed to get the chat server working:
chatserver.js
//settings var websocketPort = 1980; // start websockets var io = require('socket.io').listen(websocketPort); console.log('chat server is running on port ' + websocketPort); //websocket communication io.sockets.on('connection', function(socket){ // tell all clients who has connected var ipAddress = socket.handshake.address.address; io.sockets.emit('chat', {name: ipAddress, text: 'joined chat'}); console.log('client [' + ipAddress + '] connected'); // relay message of client to all other clients socket.on('chat', function(data){ io.sockets.emit('chat', {name: data.name, text: data.text}); }); // tell all clients who has disconnected socket.on('disconnect', function(){ io.sockets.emit('chat', {name: ipAddress, text: 'left chat'}); console.log('client [' + ipAddress + '] disconnected'); }); });
That’s all you need for simple little chat server. I think the code is pretty self-explanatory. Here are just some key points:
Read Fabian Gosebrink’s article about creating a chat client which interacts with the chat server.
Be sure to use the correct socket.io.js file for your client. You get it from the chat server directory (./node_modules/socket.io/node_modules/socket.io-client/socket.io.js)
[…] to this post I want to show you how you can set up a chat-client to a node.js-server via angular.js. We will […]
[…] node.js – Chat Server Angular.js – Chat Client with socket.io, flashing title and loading bar […]