Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Last active April 3, 2017 06:42
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 joduplessis/965052f52e508b15c7ce4f97adb826b2 to your computer and use it in GitHub Desktop.
Save joduplessis/965052f52e508b15c7ce4f97adb826b2 to your computer and use it in GitHub Desktop.
/*
* A simplistic chat relay server that pools client connections
* Written with Node, ES5 & using web sockets (Socket.io)
*/
var io = require("socket.io");
var socket = io.listen(8001);
var people = [];
// On connection start
socket.on("connection", function (client) {
connectionId = "";
client.on("join", function(joinObject) {
// See if this user exists
// If not, add them to the people list
if (!doesUserExist(joinObject)) {
connectionId = joinObject.userId;
people.push(joinObject);
client.emit("update", "You have successfully connected to the server.");
socket.sockets.emit("update", joinObject.userName + " has just joined.");
socket.sockets.emit("update-people", people);
}
});
// Send message to everybody
client.on("send-message", function(messageObject) {
socket.sockets.emit("message", messageObject);
});
// Delete the user off of the people list when disconnecting
client.on("disconnect", function() {
socket.sockets.emit("update", people[client.id] + " has left the server.");
deleteUser(connectionId);
socket.sockets.emit("update-people", people);
});
});
// Method for deleting people
function deleteUser(handle) {
for (var p=0; p<people.length; p++) {
if (handle==people[p].userId) {
console.log("Deleting "+handle+" from server.");
people.splice(p, 1);
}
}
}
// Checking for a user existing
function doesUserExist(user) {
for (var p=0; p<people.length; p++) {
if (user.userId==people[p].userId) {
console.log("User "+user.userId+" exists.");
return true;
break;
} else {
return false;
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment