Example chat application using Nodejs + ws


Previous tutorial: Example chat application using Nodejs + Websocket

With Nodejs, we can create real-time application like chat-room. We can use Socket.io, WS or Websocket. Today, we introduce a simple chat application with Nodejs + ws

Application structure:

chat nodejs ws structure

File index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>WS - Simple chat</title>

        <style>
        * { font-family:tahoma; font-size:12px; padding:0px; margin:0px; }
        p { line-height:18px; }
        div { width:500px; margin-left:auto; margin-right:auto;}
		.ulist{float: left; width: 100px; margin-top: 10px;}
        #screen { padding:5px; background:#ddd; border-radius:5px; overflow-y: scroll; border:1px solid #CCC; margin-top:10px; height: 160px; width: 350px; float: right;}
        #input { border-radius:2px; border:1px solid #ccc; margin-top:10px; padding:5px; width:400px;  }
        #status { width:88px; display:block; float:left; margin-top:15px; }
		#send { border-radius:2px; border:1px solid #ccc; margin-top:10px; padding:5px; width:70px;  }
        </style>
    </head>
    <body>
		<div>
			<div class="ulist"><ul></ul></div>
			<div id="screen"></div>
		</div>
        <div>
            <input type="text" id="input" /> <input type="button" value="send" id="send" />
        </div>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
		 
		<script src="./client.js"></script>
		 
    </body>
</html>

File client.js

function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
    	var randomPoz = Math.floor(Math.random() * charSet.length);
    	randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}

jQuery(document).ready(function($) {
 
    var content = $('#screen');
    var ws = new WebSocket('ws://localhost:8080');
	var u = null;
	if(!$.cookie('name')){
		u = prompt("What's your name?");
		while(u == ''){
			u = prompt("What's your name?");
		}
		$.cookie('name', u);
	}else{
		u = $.cookie('name');
	}
	var session = randomString(5);
    ws.onopen = function() {
        console.log('Connected');
		ws.send('/add ' + u); 
		ws.send('/session ' + session);
    };

    $('#send').click(function() {
        ws.send('/broadcast '+u+':'+$('#input').val());
		$('#input').val('');
    });
	 
    ws.onmessage = function(msg) {
        console.log('Received message from server: ' + msg.data);
		var message = msg.data;
		var cmd = '';
		var param = '';

		if(message.indexOf('/') === 0){
			cmd = message.split(' ')[0];
			param = message.replace(cmd, '');
		}
		switch(cmd){
			case '/broadcast': 
				addMessage(param);
				break;
			case '/add':
				addMessage(param+' is online');
				break;
			case '/out':
				addMessage(param+' is offline');
				break;
			case '/exists':
				alert(param+' is exists');
				u = prompt("What's your name?");
				ws.send('/add ' + u);
				$.cookie('name', u);
				break;
			case '/list':
				var users = JSON.parse(param);
				$('.ulist ul').html('');
				for(var k in users){
					$('.ulist ul').prepend('<li>' + users[k] + '</li>');
				}
			break;
		}
    }

    function addMessage(message) {
        content.prepend('<p><span>' + message + '</span></p>');
    }
	
	$('#input').keypress(function(e) {
		if(e.which == 13) {
			$(this).blur();
			$('#send').focus().click();
		}
	});
});

File server.js

var ipaddress = 'localhost';
var port = 8080;
var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({host:ipaddress, port:port})
  , users = {};
wss.broadcast = function(data) {
  for (var i in this.clients){
	this.clients[i].send(data);
  }  
};
wss.broadcasti = function(data, session) {
  for (var i in this.clients){
	if(this.clients[i].session == session)
		this.clients[i].send(data);
  }  
};
wss.broadcastni = function(data, session) {
  for (var i in this.clients){
	if(this.clients[i].session != session)
		this.clients[i].send(data);
  }  
};
wss.on('connection', function(ws) {
	ws.on('close', function ( ) {   
		wss.broadcast('/out '+ws.username);
	 
		delete users[ws.username];
		wss.broadcastni('/list '+JSON.stringify(users));	 
	});
	ws.on('message', function(message) {
		var cmd = '';
		var param = '';
		if(message.indexOf('/') === 0){
			cmd = message.split(' ')[0];
			param = message.replace(cmd, '');
		}
		switch(cmd){
			case '/add':
				if (param in users) {
					/*
					var check = false;
					for(var k in wss.clients){
					if(wss.clients[k].username == param) {
						check = true; break;
					}
					}
					if(check)*/
					wss.broadcasti('/exists '+param, ws.session);
				}else{
					users[param] = param;
					ws.username = param; 
					wss.broadcast('/list '+JSON.stringify(users));
				}
				break;
			 
			case '/session':
				ws.session = param; 
				break;
		}
		wss.broadcast(message); 
  });
   
});
console.log('Listening to ' + ipaddress + ':' + port + ' ...');

Run: npm install ws to install ws

Run: node server.js

Go to website: http://localhost/chat3/

chat nodejs ws 1

chat nodejs ws 2

Leave a Reply