Skip to content

Instantly share code, notes, and snippets.

@jkirkby91
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkirkby91/9f93ed2cf4e1aa7870e7 to your computer and use it in GitHub Desktop.
Save jkirkby91/9f93ed2cf4e1aa7870e7 to your computer and use it in GitHub Desktop.
$(function () {
"use strict";
// for better performance - to avoid searching in DOM
var content = $('#content');
var input = $('#input');
var claim = $('#claim');
var status = $('#status');
// my name sent to the server
var myName = false;
// if user is running mozilla then use it's built-in WebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
// if browser doesn't support WebSocket, just show some notification and exit
if (!window.WebSocket) {
content.html($('<p>', { text: 'Sorry, but your browser doesn\'t '
+ 'support WebSockets.'} ));
input.hide();
$('span').hide();
return;
}
// open connection
var connection = new WebSocket('ws://192.168.0.15:52042');
connection.onopen = function () {
// first we want users to enter their names
if (localStorage['username'] === null) {
console.log('empty');
} else {
console.log(localStorage['username']);
input.removeAttr('disabled');
status.text('Choose name:');
}
};
connection.onerror = function (error) {
// just in there were some problems with conenction...
content.html($('<p>', { text: 'Sorry, but there\'s some problem with your '
+ 'connection or the server is down.' } ));
};
// most important part - incoming messages
connection.onmessage = function (message) {
// try to parse JSON message. Because we know that the server always returns
// JSON this should work without any problem but we should make sure that
// the massage is not chunked or otherwise damaged.
try {
var json = JSON.parse(message.data);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message.data);
return;
}
// NOTE: if you're not sure about the JSON structure
// check the server source code above
if (json.type === 'userName') { // first response from the server with user's color
input.removeAttr('disabled');
addUser(json.data);
// from now user can start sending messages
} else if (json.type === 'room') {
input.removeAttr('disabled');
json.data.forEach(function(entry) {
addUser(entry['userName']);
console.log('whos in the room ' + entry['userName']);
});
}
else if (json.type === 'retire') {
console.log(json);
retireUser(json.data);
} else if (json.type === 'message') { // it's a single message
input.removeAttr('disabled'); // let the user write another message
addMessage(json.data.author, json.data.text,
json.data.color, new Date(json.data.time));
} else {
console.log('Hmm..., I\'ve never seen JSON like this: ', json);
}
};
/**
* Send mesage when user presses Enter key
*/
input.keydown(function(e) {
console.log('username entered');
if (e.keyCode === 13) {
var msg = $(this).val();
if (!msg) {
return;
}
// send the message as an ordinary text
connection.send(msg);
$(this).val('');
// disable the input field to make the user wait until server
// sends back response
input.attr('type', 'hidden');
status.css('display', 'none');
claim.removeAttr('style');
// we know that the first message sent from a user their name
if (myName === false) {
localStorage['username'] = msg;
console.log(localStorage['username']);
myName = msg;
}
}
});
/**
* submits users claim to point
*/
claim.click(function(e) {
console.log('submit clicked');
var msg = 1;
if (!msg) {
return;
}
connection.send(msg);
});
/**
* This method is optional. If the server wasn't able to respond to the
* in 3 seconds then show some error message to notify the user that
* something is wrong.
*/
setInterval(function() {
if (connection.readyState !== 1) {
status.text('Error');
input.attr('disabled', 'disabled').val('Unable to comminucate '
+ 'with the WebSocket server.');
}
}, 3000);
/**
* Add user ball to the chat window
*/
function addUser(author) {
$( "#content" ).append("<span class='circle red' id="+author+"></span>");
$("#" +author).text(author);
}
/**
* Add message to the chat window
*/
function addMessage(userName) {
$('#' + userName).addClass('green');
console.log(userName + 'hits first');
}
/**
* remove a user from the window
* @param userName
*/
function retireUser(userName) {
console.log(userName);
console.log(123);
$('#' + userName).remove();
console.log( $('#' + userName));
console.log(userName + ' cant handle the pressure');
}
});
"use strict";
// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'doorgame';
// Port where we'll run the websocket server
var webSocketsServerPort = 52042;
// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');
/**
* Global variables
*/
// latest 100 messages
var history = [ ];
// list of currently connected clients (users)
var clients = [ ];
// list of usernames in room
var room = [ ];
/**
* Helper function for escaping input strings
*/
function htmlEntities(str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')
.replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function broadcastMessage(json_string) {
for (var v=0; v < clients.length; v++) {
clients[v].sendUTF(json_string);
}
}
/**
* HTTP server
*/
var server = http.createServer(function(request, response) {
// Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});
/**
* WebSocket server
*/
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server. WebSocket request is just
// an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
httpServer: server
});
// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
// accept connection - you should check 'request.origin' to make sure that
// client is connecting from your website
// (http://en.wikipedia.org/wiki/Same_origin_policy)
var connection = request.accept(null, request.origin);
// we need to know client index to remove them on 'close' event
var index = clients.push(connection) - 1;
var userName = false;
console.log((new Date()) + ' Connection accepted.');
// send back room
if (room.length > 0) {
connection.sendUTF(JSON.stringify({ type: 'room', data: room}));
}
// user sent some message
connection.on('message', function(message) {
if (message.type === 'utf8') { // accept only text
if (userName === false) { // first message sent by user is their name
// remember user name
userName = htmlEntities(message.utf8Data);
// get random color and send it back to the user
// connection.sendUTF(JSON.stringify({ type:'color', data: userColor }));
console.log((new Date()) + ' User is known as: ' + userName);
room.push({userName:userName,score:0});
var userName_json = JSON.stringify({ type:'userName', data: userName });
broadcastMessage(userName_json);
console.log(room);
} else { // log and broadcast the message
console.log((new Date()) + ' Received Message from '
+ userName + ': ' + message.utf8Data);
// we want to keep history of all sent messages
var obj = {
time: (new Date()).getTime(),
author: userName
};
history.push(obj);
history = history.slice(-100);
// broadcast message to all connected clients
var messgae_json = JSON.stringify({ type:'message', data: obj });
broadcastMessage(messgae_json);
}
}
});
// user disconnected
connection.on('close', function(connection) {
console.log(userName);
console.log(room);
console.log(123);
if (userName !== false) {
console.log('user name is not false lets splice');
console.log((new Date()) + " Peer "
+ connection.remoteAddress + " disconnected.");
clients.splice(index, 1);
room.splice(index, 1);
console.log(456);
console.log(userName);
console.log(room);
var userName_json = JSON.stringify({ type:'retire', data: userName });
broadcastMessage(userName_json);
} else {
console.log('cant do anything userName is false');
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment