Skip to content

Instantly share code, notes, and snippets.

@symm symm/basic-server.js
Created Dec 18, 2017

Embed
What would you like to do?
"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');
/**
* 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 + '.');
var connection = request.accept(null, request.origin);
console.log((new Date()) + ' Connection accepted.');
// send some stuff
connection.sendUTF(JSON.stringify( { foo: 'bar' } ));
// client sent some stuff
connection.on('message', function(message) {
console.log('Message received' + JSON.stringify(message));
});
// client disconnected
connection.on('close', function(connection) {
console.log((new Date()) + " Peer "
+ connection.remoteAddress + " disconnected.");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.