Skip to content

Instantly share code, notes, and snippets.

@prehensile
Created May 8, 2018 09:09
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 prehensile/c6864a78906369bd14c89e3c15f2b59c to your computer and use it in GitHub Desktop.
Save prehensile/c6864a78906369bd14c89e3c15f2b59c to your computer and use it in GitHub Desktop.
Bits and pieces of gig'n'mix
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
"use strict";
// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'node-chat';
// Port where we'll run the websocket server
var webSocketsServerPort = 1337;
// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');
/**
* Global variables
*/
// list of currently connected clients (users)
var clients = [ ];
/**
* 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;
console.log((new Date()) + ' Connection accepted.');
// user sent some message
connection.on('message', function(message) {
if (message.type === 'utf8') { // accept only text
var dat = message.utf8Data;
console.log( (new Date()) + ' message from ' + request.remoteAddress +": " + dat );
// broadcast message to all connected clients
for (var i=0; i < clients.length; i++) {
clients[i].sendUTF( dat );
}
}
});
// user disconnected
connection.on('close', function(connection) {
clients.splice(index, 1);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment