// to keep the session id var sessionId = ''; // name of the client var name = ''; // socket connection url and port var socket_url = '172.16.34.226'; var port = '8080'; $(document).ready(function() { $("#form_submit, #form_send_message").submit(function(e) { e.preventDefault(); join(); }); }); var webSocket; /** * Connecting to socket */ function join() { // Checking person name if ($('#input_name').val().trim().length <= 0) { alert('Enter your name'); } else { name = $('#input_name').val().trim(); $('#prompt_name_container').fadeOut(1000, function() { // opening socket connection openSocket(); }); } return false; } /** * Will open the socket connection */ function openSocket() { // Ensures only one connection is open at a time if (webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED) { return; } // Create a new instance of the websocket webSocket = new WebSocket("ws://" + socket_url + ":" + port + "/WifiChat/chat?name=" + name); /** * Binds functions to the listeners for the websocket. */ webSocket.onopen = function(event) { $('#message_container').fadeIn(); if (event.data === undefined) return; }; webSocket.onmessage = function(event) { // parsing the json data parseMessage(event.data); }; webSocket.onclose = function(event) { alert('Error! Connection is closed. Try connecting again.'); }; } /** * Sending the chat message to server */ function send() { var message = $('#input_message').val(); if (message.trim().length > 0) { sendMessageToServer('message', message); } else { alert('Please enter message to send!'); } } /** * Closing the socket connection */ function closeSocket() { webSocket.close(); $('#message_container').fadeOut(600, function() { $('#prompt_name_container').fadeIn(); // clearing the name and session id sessionId = ''; name = ''; // clear the ul li messages $('#messages').html(''); $('p.online_count').hide(); }); } /** * Parsing the json message. The type of message is identified by 'flag' node * value flag can be self, new, message, exit */ function parseMessage(message) { var jObj = $.parseJSON(message); // if the flag is 'self' message contains the session id if (jObj.flag == 'self') { sessionId = jObj.sessionId; } else if (jObj.flag == 'new') { // if the flag is 'new', a client joined the chat room var new_name = 'You'; // number of people online var online_count = jObj.onlineCount; $('p.online_count').html( 'Hello, ' + name + '. ' + online_count + ' people online right now') .fadeIn(); if (jObj.sessionId != sessionId) { new_name = jObj.name; } var li = '