} //==========WEB SOCKET SERVER============ var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ' Server is listening on port 8080'); }); var wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false }); function originIsAllowed(origin){ //本当はここでリクエストオリジンを捌く return true; } wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } //app-protocolによる、当該オリジンからのアクセスを許可
// socketPort: socketPort // }); // }); /* Server */ app.listen(port); /* WebSocket Server */ var server = http.createServer(app); var clients = []; // création d'un tableau de clients (utilisateurs) // initialisation du serveur websocket (ws) var wsServer = new websocketServer({ httpServer: server }); server.listen(socketPort, function() { console.log("Server is running !" + socketPort); // message dans la console }); // ---------------------------------------------------------------------------------------------------------------------------------------- // GESTION PAR LE WS SERVER // ---------------------------------------------------------------------------------------------------------------------------------------- // se connecte au serveur wsServer.on('request', function(request) { var connection = request.accept(null, request.origin);
/** * 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 escuchando el puerto " + 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()) + ' Conexión desde el 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;
var http = require('http'); var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8888, function() { console.log((new Date()) + ' Server is listening on port 8888'); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } process.stdin.resume(); process.stdin.setEncoding('utf8'); var util = require('util'); process.stdin.on('data', function(text) {
var http = require('http'); var activeUsersList = {}; var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8888, function() { console.log((new Date()) + ' Server is listening on port 8888'); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject();
var port = 8888; var WebSocketServer = require('websocket').server; var http = require('http'); var g_offers = {}; var server = http.createServer(function(request, response) { response.end('This is a WebSocket server.'); }); server.listen(port, function() { console.log('Server running at http://localhost:' + port); }); // create the server wsServer = new WebSocketServer({ httpServer: server }); var g_offer_connections = {}; var g_next_id = 1; wsServer.on('request', function(request) { var connection = request.accept('peer-protocol', request.origin); connection.id = g_next_id++; console.log('connect id:', connection.id); connection.on('error', function (error) { console.error('error: ', connection.id, error); }); connection.on('open', function () {
var http = require('http'); var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(1339, function() { console.log((new Date()) + ' Server is listening on port 1339'); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
grunt.registerTask('reload', "Reload connected clients when a file has changed.", function (target) { var server = servers[target ? target:'default']; if (server) { var errorcount = grunt.fail.errorcount; // throttle was needed early in development because of rapid triggering by the watch task. Not sure if it's still necessary if (!throttle) { if (target) { taskEvent.emit('reload:' + target); } else { taskEvent.emit('reload'); } throttle = true; setTimeout(function () { throttle = false; }, 2000); grunt.log.writeln("File updated. Reload triggered."); } else { return; } // Fail task if there were errors. if (grunt.fail.errorcount > errorcount) { return false; } } else { // start a server that can send a reload command over a websocket connection. var middleware = []; this.requiresConfig('reload'); // Get values from config, or use defaults. var config = target ? grunt.config(['reload', target]) : grunt.config('reload'); var port = config.port || 8001; var base = path.resolve(grunt.config('server.base') || '.'); var reloadClientMarkup = '<script src="/__reload/client.js"></script>'; if (!target) { target = 'default'; } if (config.proxy) { var proxyConfig = config.proxy; var options = { target:{ host:proxyConfig.host || 'localhost', port:proxyConfig.port || grunt.config('server.port') || 80, path:proxyConfig.path || '/' // not yet supported by http-proxy: https://github.com/nodejitsu/node-http-proxy/pull/172 } }; var proxy = new httpProxy.HttpProxy(options); var targetUrl = 'http://' + options.target.host + ':' + options.target.port + options.target.path; // modify any proxied HTML requests to include the client script middleware.unshift(connect( function (req, res) { if (proxyConfig.includeReloadScript !== false) { // monkey patch response, postpone header var _write = res.write, _writeHead = res.writeHead, _end = res.end, _statusCode, _headers, tmpBuffer; res.write = function (data) { if (tmpBuffer) { tmpBuffer.push(data); } else { _write.call(res, data); } }; res.writeHead = function (statusCode, headers) { _statusCode = statusCode; _headers = headers; if (/html/.test(_headers["content-type"])) { // defer html & headers tmpBuffer = buffers(); } else { _writeHead.call(res, _statusCode, _headers); } }; res.end = function () { if (tmpBuffer) { var html = tmpBuffer.toString(); html = html.replace('</body>', reloadClientMarkup + '</body>'); // since nodejs only support few charsets, we only support // UTF-8 at this moment. // TODO: support other charsets besides UTF-8 _headers['content-length'] = Buffer.byteLength(html, 'utf-8'); _writeHead.call(res, _statusCode, _headers); _write.call(res, html); } _end.call(res); }; } proxy.proxyRequest(req, res); } )); grunt.log.writeln("Proxying " + targetUrl); } else { middleware.unshift(connect.static(base, { redirect:true })); } if (config.iframe) { // serve iframe middleware.unshift(route('GET', '/', function (req, res, next) { var targetUrl = config.iframe.target; res.end('<html><body style="margin:0;"><iframe style="border:none;" height="100%" width="100%" src="' + targetUrl + '"></iframe>' + reloadClientMarkup + '</body></html>'); })); } if (config.liveReload) { // required by LR 2.x middleware.unshift(route('GET', /\/livereload.js(\?.*)?/, function (req, res, next) { res.write('__reloadServerUrl="ws://localhost:' + config.port + '";\n'); fs.createReadStream(__dirname + "/include/reloadClient.js").pipe(res); })); } // provide route to client js middleware.unshift(route('GET', '/__reload/client.js', function (req, res, next) { fs.createReadStream(__dirname + "/include/reloadClient.js").pipe(res); // use connect.static.send ? })); // if --debug was specified, enable logging. if (grunt.option('debug')) { connect.logger.format('grunt', ('[D] reloadServer :method :url :status ' + ':res[content-length] - :response-time ms').blue); middleware.unshift(connect.logger('grunt')); } // kick-off server = connect.apply(null, middleware).listen(port); servers[target] = server; if (!servers.default) { servers.default = server; } var wsServer = new WebSocketServer({ httpServer:server, autoAcceptConnections:true }); wsServer.on('connect', function (request) { var connection = request; //.accept(); //.accept('*', request.origin); console.log((new Date()) + ' Connection accepted.'); connection.on('message', function (message) { if (message.type === 'utf8') { console.log('Received Message: ' + message.utf8Data); if (message.utf8Data === 'trigger') { grunt.helper('trigger', grunt.config('trigger.watchFile')); connection.sendUTF('Update triggered'); } // LiveReload support if (message.utf8Data.match(/^http:\/\//)) { connection.sendUTF("!!ver:1.6;"); } if (message.utf8Data.match(/{.*/)) { var handshake = "{ command: 'hello', protocols: [ " + "'http://livereload.com/protocols/official-7', " + "'http://livereload.com/protocols/2.x-origin-version-negotiation', " + "'http://livereload.com/protocols/2.x-remote-control'" + "], serverName: 'grunt-reload', }"; connection.sendUTF(handshake); } } }); connection.on('close', function (reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); }); taskEvent.on('reload', function() { handleReload(wsServer); }); if (target) { taskEvent.on('reload:' + target, function() { handleReload(wsServer, target); }); } grunt.log.writeln("reload server running at http://localhost:" + port); } });
} var httpServer = server_http.createServer( function(request, response){ var urlInfo = url.parse(request.url, true) var page = urlInfo.pathname if (page == "/message"){ } if (page === "/"){ getIndex(response); } if (page === "/main.js"){ getMainJs(response); } }); httpServer.listen(8080); wsServer = new WebSocketServer({ httpServer: httpServer, }); wsServer.on('request', function(request) { var connection = request.accept(null, request.origin); connection.on('message', function(message) { wsServer.broadcastUTF(message.utf8Data); }); connection.on('close',function(){ console.log("bye bye "); }); });
var Http = require( 'http' ); // Port name looked up in Arduino IDE var ARDUINO_PORT = '/dev/tty.usbmodem1411'; // Web Sockets start life as HTTP requests var server = Http.createServer( function( request, response ) { // Process HTTP request // Just Web Sockets here so nothing to see here // Move along! } ); server.listen( 8080, function() {;} ); // Create Web Socket server var socket = new WebSocketServer( { httpServer: server, fragmentOutgoingMessages: false } ); var clients = []; // Handle Web Socket requests from browser socket.on( 'request', function( request ) { var connection = request.accept( null, request.origin ); // Keep track of the clients clients.push( connection ); console.log( 'New Web Socket connection' ); // Close the connection // Update client list connection.on( 'close', function( connection ) {
}); // Port of the WebSocket server var webSocketsServerPort = 8000; // Helper function for escaping input strings function htmlEntities(str) { return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); } // HTTP server var websocketHTTPserver = http.createServer().listen(webSocketsServerPort, function() { console.log("WebSocketsServer is listening on port " + webSocketsServerPort); }); // The WebSocket server is bound to HTTP server var wsServer = new webSocketServer({ httpServer : websocketHTTPserver }); // Extracts the sid from the cookies function getSidFromCookies(cookies) { var filtered = cookies.filter(function(obj) { return obj.name == 'connect.sid'; }); return filtered.length > 0 ? unescape(filtered[0].value).substr(0, 24) : null; } // Keeps all open WebSocket connections var connections = {}; // This callback function is called every time someone // tries to connect to the WebSocket server
app.use(express.static(path.resolve(__dirname + '/../'))) app.get('/', function (req, res) { res.sendFile(path.resolve(__dirname + '/../index.html')) }) app.get('/websocket', function (req, res) { res.send({ websocket_support: true, }) }) wsServer = new ws({ httpServer: server }) var nixJsonAPIScript = __dirname + '/linux_json_api.sh' function getPluginData(pluginName, callback) { var command = spawn(nixJsonAPIScript, [ pluginName, '' ]) var output = [] command.stdout.on('data', function(chunk) { output.push(chunk.toString()) }) command.on('close', function (code) { callback(code, output) })
var html = fs.readFile("../cards/Polarity/"+result.cardName+".txt", "utf8", function(error, data) { result.html = data; connection.sendUTF(JSON.stringify(result)); }) return result }); } catch (err) { connection.sendUTF("card does not exist in our records"); } } // create the server wsServer = new WebSocketServer({ httpServer: server }); // WebSocket server wsServer.on('request', function(request) { var connection = request.accept(null, request.origin); // This is the most important callback for us, we'll handle // all messages from users here. connection.on('message', function(message) { if (message.type === 'utf8') { console.log('finding the card') cardData = cardSearch(message.utf8Data, connection) } }); connection.on('close', function(connection) {
function init(server) { config.plugins.forEach(function (p) { var instanceName = p.instanceName || p.plugin; var plug = new (require('./../plugins/' + p.plugin))(); plugins[instanceName] = plug; plugins[instanceName].setName(instanceName); plugins[instanceName].setHandler(notifySubscribers); if ( plugins[instanceName].setup && config.pluginConfig[instanceName] ) { plugins[instanceName].setup(config.pluginConfig[instanceName]); } }); Object.keys(plugins).forEach(function (p) { var datasets = plugins[p].test(); if ( datasets instanceof Array ) { subscribers[p] = {}; datasets.forEach(function (ds) { validPlugins.push(p + '.' + ds); subscribers[p][ds] = []; }); } }); validPlugins.sort(); wsServer = new WebSocketServer({ httpServer: server }); wsServer.on('request', function(req) { var connection = req.accept(null, req.origin); connection.sendUTF(JSON.stringify({type: 'plugins', valid: validPlugins})); connection.on('message', function(m) { var mess = JSON.parse(m.utf8Data); switch(mess.type) { case 'subscribe': var mp = mess.plugin.split(/\./); var plugin = mp[0]; var graph = mp.slice(1).join('.'); if ( subscribers[plugin] && subscribers[plugin][graph] && subscribers[plugin][graph].indexOf(connection) === -1 ) { subscribers[plugin][graph].push(connection); } else { connection.sendUTF(JSON.stringify({type: 'error', message: 'No such plugin'})); } break; case 'unsubscribe': var mp = mess.plugin.split(/\./); var plugin = mp[0]; var graph = mp.slice(1).join('.'); subscribers[plugin][graph] = subscribers[mp[0]][mp[1]].filter(function (ar) { return (ar != connection); }); break; } }); connection.on('close', function(conn) { validPlugins.forEach(function (pl) { var mp = pl.split(/\./); var plugin = mp[0]; var graph = mp.slice(1).join('.'); subscribers[plugin][graph] = subscribers[plugin][graph].filter(function (ar) { return (ar != connection); }); }); }); }); // We want to sleep a little to align the graphs with whole seconds. It's prettier. var _ws = (Math.ceil(new Date().getTime() / 1000) * 1000) - new Date().getTime(); setTimeout(function () { setInterval(function () { Object.keys(subscribers).forEach(function (pl) { plugins[pl].run(); }); }, 1000); }, _ws); }
var WebSocketServer = require('websocket').server; var http = require('http'); var connections = []; var server = http.createServer(function(request, response) { //process HTTP request. Since we're writing just WebSockets server // we don't have to implement anything. }); server.listen(1337,function(){}); wsServer = new WebSocketServer({ httpServer: server }); wsServer.on('request', function(request) { var connection = request.accept(null, request.origin); connections.push({id: '', pseu: '', socket: connection}); console.log("Server: New peer is connected!"); //we'll handle all messages from users here connection.on('message', function(message) { if (message.type === 'utf8') { var msg = JSON.parse(message.utf8Data); var caller = msg.caller; var callee = msg.callee; var callerpseu = msg.callerpseu; if(msg.data.type === 'join') { for(var i=0; i<connections.length; i++) { // Associate Socket <-> ID if(connections[i].socket === connection) { connections[i].id = caller;
connection.on('message', function(message) { wsServer.broadcastUTF(message.utf8Data); });
key: sslKey, cert: sslCert } //var server = http.createServer(options, function(request, response) { var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(port, function() { console.log((new Date()) + ' Server is listening on port ' + port); }); wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false }); function timerSend() { var strData; var data = {sessionId:"1234", CUID:"5678", uri:"/device/v1/firmwareversion"}; strData = JSON.stringify(data); commandConnection.send(strData); console.log("send data"); setTimeout(timerSend, 1000); }
// create the server function createServerTaChatte(httpserver) { var conn; wsServer = new WebSocketServer({ httpServer: httpserver }); // WebSocket server wsServer.on('request', function(request) { conn = request.accept('sharks', request.origin); console.log("connected"); conn.on('message', function(message) { console.log('got message', message); maxParam = parseInt(message.utf8Data, 10); if (AMSTERDAMConnection) { AMSTERDAMConnection.send(maxParam); } }); conn.on('close', function(connection) { conn = undefined; console.log("close"); }); }); wsServer.sendPlay = function(instID, height, duration) { console.log('send play message', instID, height, duration); if (!conn) { console.log('but no-one is listening :('); return; } conn.sendUTF(JSON.stringify({ instrument: instID, height: height, duration: duration})); }; var WebSocketClient = require('websocket').client; var AMSTERDAMConnection; var client = new WebSocketClient(); client.on('connectFailed', function(error) { console.log('Connect Error: ' + error.toString()); }); client.on('connect', function(connection) { AMSTERDAMConnection = connection; console.log('WebSocket client connected'); connection.on('error', function(error) { console.log("Connection Error: " + error.toString()); }); connection.on('close', function() { console.log('Connection Closed'); }); connection.on('message', function(message) { if (conn) { console.log(message); conn.send(message.utf8Data); } }); }); client.connect('ws://mhd.paul.cx:81/', 'sharks'); return wsServer; }
var express = require('express'); var positions = {}; var total = 0; var connectedSocket = {}; var app = express(); app.use(express.static('public')); var server = app.listen(3000, function () { console.log((new Date()) + ' Server is listening on port 3000'); }); var ws = new WebSocketServer({ httpServer : server, autoAcceptConnections : false }); ws.on('request', function (request) { var socket = request.accept('echo-protocol', request.origin); console.log((new Date()) + ' Connection accepted.'); // you give the socket an id socket.id = ++total; connectedSocket[socket.id] = socket; // you send the positions of everyone else socket.sendUTF(JSON.stringify(positions)); socket.on('message', function (msg) { try { // { type: 'utf8', utf8Data: '{"x":127,"y":304}' }
}); // Poker App specific Variables var pokerConnection = require('./poker-connection.js'), pokerBroadcaster = require('./poker-broadcaster.js'), pokerUsers = require('./poker-users.js'), pokerUserstory = require('./poker-userstory.js'), pokerCards = require('./poker-cards.js'); // WebSocket Server console.log('Creating WebSocket Server'); wsServer = new WebSocketServer({ httpServer: httpServer, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); pokerBroadcaster.init(wsServer); var pokerLoginListener = function(messageData) { var user, sha1sum, sendData; // For callbacks connection = this.connection;
prepros.factory('liveServer', function (config) { 'use strict'; var express = require('express'), app = express(), WebSocketServer = require('websocket').server, urls = [], serverProjects = []; //Start listening var httpServer = app.listen(5656); //Start websocket server for automatic browser refresh var wsServer = new WebSocketServer({ httpServer: httpServer, autoAcceptConnections: false }); //Send the list of urls to refresh to extension on connect wsServer.on('request', function (request) { request.accept('', request.origin); wsServer.broadcast(angular.toJson({urls: urls})); }); //Generates live preview url function getLiveUrl(project) { if (project.config.useCustomServer) { var url = require('url'); var parsed = url.parse(project.config.customServerUrl); return parsed.protocol + '//' + parsed.host; } else { return 'http://localhost:5656/' + project.config.serverUrl + '/'; } } //Live reload middleware inspired by https://github.com/intesso/connect-livereload app.use(function (req, res, next) { var writeHead = res.writeHead; var write = res.write; var end = res.end; var path = require('path'); var url = require('url'); var filepath = url.parse(req.url).pathname; filepath = filepath.slice(-1) === '/' ? filepath + 'index.html' : filepath; var html = ['.html', '.htm']; if (!_.contains(html, path.extname(filepath))) { return next(); } res.push = function (chunk) { res.data = (res.data || '') + chunk; }; res.inject = res.write = function (string, encoding) { if (string !== undefined) { var body = string instanceof Buffer ? string.toString(encoding) : string; var snippet = '<script>' + '(function(){var a=document.createElement("script");document.querySelector("body").appendChild(a);' + 'a.src="http://" + window.location.host + "/lr/livereload.js?snipver=1&host=" + window.location.hostname + "&port=25690"})();' + '</script>'; res.push(body.replace(/<\/body>/, function (w) { return snippet + w; })); } return true; }; res.end = function (string, encoding) { res.writeHead = writeHead; res.end = end; var result = res.inject(string, encoding); if (!result) { return res.end(string, encoding); } if (res.data !== undefined && !res._header) { res.setHeader('content-length', Buffer.byteLength(res.data, encoding)); } res.end(res.data, encoding); }; next(); }); //function to add project to server function startServing(projects) { urls = []; serverProjects = []; _.each(projects, function (project) { var projectUrl = '/' + project.config.serverUrl + '/'; app.use(projectUrl, express.static(project.path)); app.use(projectUrl, express.directory(project.path, {icons: true})); if (!project.config.useCustomServer) { serverProjects.push({ name: project.name, url: projectUrl}); } if (project.config.useCustomServer) { urls.push(getLiveUrl(project)); } }); //Send data to browser extensions wsServer.broadcast(angular.toJson({urls: urls})); } var refreshServer = new WebSocketServer({ //Live reload connection port httpServer: app.listen(25690), autoAcceptConnections: false }); //Index page for projects app.set('views', config.basePath + '/templates/live-server'); app.set('view engine', 'jade'); app.get('/', function (req, res) { res.render('index', { projects: serverProjects }); }); app.use('/lr/', express.static(config.basePath + '/vendor/')); app.use('/lr/', express.directory(config.basePath + '/vendor/')); refreshServer.on('request', function (request) { request.accept('', request.origin); refreshServer.broadcast(("!!ver:1.6")); }); function refresh(file) { var data = JSON.stringify([ 'refresh', { path: file, apply_js_live: false, apply_css_live: true } ]); refreshServer.broadcast(data); } //Return return { startServing: startServing, getLiveUrl: getLiveUrl, refresh: refresh }; });
app.listen(port, host, function(err) { if(err) throw err; // Assign the collections state.gameCollection = db.collection('game'); state.boardCollection = db.collection('board'); state.sessionsCollection = db.collection('sessions'); state.playersCollection = db.collection('players'); // Websocket server var wsServer = new WebSocketServer({ httpServer: app, // Firefox 7 alpha has a bug that drops the // connection on large fragmented messages fragmentOutgoingMessages: false }); // A new connection from a player wsServer.on('request', function(request) { // Parse the cookie and grab session id and player name var cookie = parseCookie(request.httpRequest.headers['cookie']); var sessionId = cookie['connect.sid']; var playerName = cookie['_mongoman_name']; // Perfor an upsert to insert a new session state.sessionsCollection.update({name:playerName}, {$set: {id: sessionId, name:playerName, b:new ObjectID()}}, {upsert:true}); // Accept the connection var connection = request.accept('game', request.origin); // Add a connection counter id connection.connectionId = parseInt(format("%s%s", process.pid, connectionIdCounter++)); // Save the connection to the current state state.connections[connection.connectionId] = connection; // Handle closed connections connection.on('close', function() { cleanUpConnection(state, this); }); // Handle incoming messages connection.on('message', function(message) { // All basic communication messages are handled as JSON objects // That includes the request for status of the board. var self = this; // Handle game status messages if(message.type == 'utf8') { // Save stats about the data statCollector.passThroughWrite("incoming", message.utf8Data); // Decode the json message and take the appropriate action var messageObject = JSON.parse(message.utf8Data); // Parse the cookie var cookie = parseCookie(request.httpRequest.headers['cookie']); // Grab the session id var sessionId = cookie['connect.sid']; // If initializing the game if(messageObject['type'] == 'initialize') { // Grab the username based on the session id and initialize the board state.sessionsCollection.findOne({id:sessionId}, function(err, session) { if(err) throw err; session = typeof session == 'undefined' || session == null ? {} : session; initializeBoard(state, session, self); }) } else if(messageObject['type'] == 'dead') { updateMongomanDeathStats(state, self, messageObject, sessionId); // Kill the board so we can start again killBoard(state, self); } else if(messageObject['type'] == 'mongowin') { // Update mongoman win stats updateMongomanWinStats(state, self, messageObject, sessionId); // Signal mongoman won mongomanWon(state, self); // Kill the board so we can start again killBoard(state, self); } else if(messageObject['type'] == 'ghostdead') { // Update player stats updateGhostDeadStats(state, self, sessionId); // Signal ghost is dead ghostDead(state, self, messageObject); } else if(messageObject['type'] == 'powerpill') { var value = messageObject['value']; // Retrieve the board by id from cache var boardId = state.boardIdByConnections[self.connectionId]; // Retrieve the game stats for the board var gameState = state.gameStatesByBoardId[boardId]; if(gameState == null) { state.gameStatesByBoardId[boardId] = {}; gameState = state.gameStatesByBoardId[boardId]; } // If we have game stats update them if(gameState) { gameState[self.connectionId]['powerpill'] = value; } var keys = Object.keys(gameState); // validate if we have a collision for(var i = 0; i < keys.length; i++) { var key = keys[i]; // Set all ghosts to alive if(value == false && !gameState[key].mongoman) { gameState[key]['dead'] = false; } // If it's not the originator set the powerpill in play if(key != self.connectionId) { state.connections[key].sendUTF(statCollector.passThroughWrite('powerpill', JSON.stringify({state:'powerpill', value:value}))); } } } else if(messageObject['type'] == 'movement') { // Unpack object var position = messageObject['object']; var mongoman = messageObject['mongoman']; // Retrieve the board by id from cache var boardId = state.boardIdByConnections[self.connectionId]; // Get the connectionid list var connectionIds = state.connectionsByBoardId[boardId]; // Retrieve the game stats for the board var gameState = state.gameStatesByBoardId[boardId]; if(gameState == null) { state.gameStatesByBoardId[boardId] = {}; gameState = state.gameStatesByBoardId[boardId]; } // Fire the move command to all boards to animate the ghosts for(var i = 0; i < connectionIds.length; i++) { // Fire off message to all the other players if(self.connectionId != connectionIds[i]) { var role = mongoman ? "m" : "g"; // Mongoman or ghost state.connections[connectionIds[i]].sendUTF(statCollector.passThroughWrite('movement', JSON.stringify({ id: self.connectionId, b: boardId, role: role, state: 'n', pos: { x: position.x, y: position.y, accx: position.accx, accy: position.accy, facing: position.facing, xpushing: position.xpushing, ypushing: position.ypushing } }))); } } // If we have game stats update them if(gameState) { if(gameState[self.connectionId] == null) { gameState[self.connectionId] = {mongoman: mongoman, pos: position, dead: false, powerpill:false}; } else{ gameState[self.connectionId] = {mongoman: mongoman, pos: position, dead: gameState[self.connectionId]["dead"], powerpill:gameState[self.connectionId]["powerpill"]}; } } // Don't respond if the game is over if(gameState[self.connectionId].dead) return; // Fetch the power pill state for this connection var powerpill = gameState[self.connectionId].powerpill; // Iterate over all the users var keys = Object.keys(gameState); // validate if we have a collision for(var i = 0; i < keys.length; i++) { var key = keys[i]; if(key != self.connectionId) { // Get the position var _player = gameState[key]; var _powerpill = _player.powerpill; var _mongoman = _player.mongoman; var _position = _player.pos; // If we have collision and either the current player or the other player is a ghost if(_position.x < (position.x + 5) && _position.x > (position.x - 5) && _position.y < (position.y + 5) && _position.y > (position.y - 5) && (mongoman == true || _mongoman == true)) { // Check if we have a powerpill situation and kill ghost if we do if(_powerpill == true || powerpill == true) { // Object to set dead var _setDeadObject = !_mongoman ? _player : gameState[self.connectionId]; // Return if this user is dead if(_setDeadObject['dead']) return; // Set player dead _setDeadObject['dead'] = true; // What id to send var _connectionId = !_mongoman ? key : self.connectionId; // Message all players that we are dead for(var j = 0; j < connectionIds.length; j++) { state.connections[connectionIds[j]].sendUTF(statCollector.passThroughWrite('ghostdead', JSON.stringify({state:'ghostdead', id:_connectionId}))); } // return; } else { // Set all items to dead for(var j = 0; j < keys.length; j++) { gameState[keys[j]].dead = true; } // Set current connection dead gameState[self.connectionId].dead = true; // Kill the board killBoard(state, self); // Short cut the method return; } } } } } } }); }); });
var http = require ('http'); var WebSocketServerConstructor = require('websocket').server; var big_history = require('./big_history'); var Server = http.createServer(); var WebSocketServer = new WebSocketServerConstructor({ httpServer: Server, autoAcceptConnections: true, fragmentationThreshold: 104857600 }); WebSocketServer.on('connect', function(connection) { console.log((new Date()) + 'Peer ' + connection.remoteAddress + ' Connection accepted.'); connection.sendUTF(JSON.stringify(big_history)); connection.on('close', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected. (' + description + ')'); }); }); Server.listen(4080, '0.0.0.0'); console.log((new Date()) + ' Server start.');
function pickRandom(seq) { return seq[Math.floor(Math.random() * seq.length)]; } function startServer(port, host) { server.listen(port, host, function() { logger.info('HUB Server listening on port ' + port + " interface: " + host); }); } var wsServer = new WebSocketServer({ httpServer: server, // 10Mb max size (1Mb is default, maybe this bump is unnecessary) maxReceivedMessageSize: 0x1000000, // The browser doesn't seem to break things up into frames (not sure what this means) // and the default of 64Kb was exceeded; raised to 1Mb maxReceivedFrameSize: 0x100000, // Using autoaccept because the origin is somewhat dynamic // FIXME: make this smarter? autoAcceptConnections: false }); function originIsAllowed(origin) { // Unfortunately the origin will be whatever page you are sharing, // which could be any origin return true; } var allConnections = {}; var connectionStats = {};
if (err) { response.writeHead(500); return response.end('Error loading index.html'); } response.writeHead(200); response.end(data); }); }); server.listen(1337, function() { console.log((new Date()) + " Server is listening on port 1337"); }); // create the server wsServer = new WebSocketServer({ httpServer: server }); function sendCallback(err) { if (err) console.error("send() error: " + err); } // 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(' Connection ' + connection.remoteAddress); clients.push(connection); // This is the most important callback for us, we'll handle
//console.log(twitterClient); var handShakeServer = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); handShakeServer.listen(8080, function() { console.log((new Date()) + ' Socket server is listening on port 8080'); }); var socketServer = new WebSocketServer({ httpServer: handShakeServer, autoAcceptConnections: false }); function originIsAllowed(origin){ if (origin == "twitterQuery"){ return true; } return false; } socketServer.on('request', function(request){ if (!originIsAllowed(request.origin)){ request.reject(); console.log((new Date()) + 'Connection from origin ' + request.origin + ' rejected.')
exports.createServer = function(config) { var ipAddr =undefined; var ifaces=require('os').networkInterfaces(); for (var dev in ifaces) { ifaces[dev].forEach(function(details){ if (details.family=='IPv4' && !details.internal) { ipAddr=details.address; } }); } console.log("host ip: "+ipAddr); var wsServer = new WebSocketServer(config); var hostConnection; //game host connection var controlConnection = {}; // hold the controlConnections wsServer.on('request', function(request) { //request comming //distinguish host from gamepad by request.requestedProtocols[0] if (request.requestedProtocols[0] === 'host') { //host connection //console.log("request host"); hostConnection = request.accept('host', request.origin); hostConnection.sendUTF(JSON.stringify({ msg: "connected", data: {hostIP:ipAddr} })); for(var i in controlConnection) { controlConnection[i].sendUTF(JSON.stringify({ msg: "redirect", data: 0 })); } ; hostConnection.on('message', function(message) { var command = JSON.parse(message.utf8Data); if ((message.type === 'utf8') && controlConnection[command.uid] && controlConnection[command.uid].connected) { controlConnection[command.uid].sendUTF(JSON.stringify({ msg: command.msg, data: command.data })); } }); console.log(hostConnection.remoteAddress + " connected - Protocol Version " + hostConnection.webSocketVersion); // Handle closed connections hostConnection.on('close', function() { console.log(hostConnection.remoteAddress + " disconnected"); // wsServer.closeAllConnections(); console.log("game exit, disconnect all controler"); }); } else if (request.requestedProtocols[0] === 'control') { //controler if (hostConnection && hostConnection.connected) { var uid = request.requestedProtocols[1]; var connection = request.accept('control', request.origin); connection.sendUTF(JSON.stringify({ msg: "connected", data: request.requestedProtocols })); console.log(connection.remoteAddress + " connected - Protocol Version " + connection.webSocketVersion); connection.on('close', function() { console.log(connection.remoteAddress + " disconnected"); if (hostConnection && hostConnection.connected) { hostConnection.sendUTF(JSON.stringify({ msg: 'stop', data: 'gamepadRemoved' })); hostConnection.sendUTF(JSON.stringify({ msg: 'gamepadRemoved', data: uid })); } console.log("game stop"); }); // Handle incoming messages from controler,and send it to host connection.on('message', function(message) { if (message.type === 'utf8') { var command = JSON.parse(message.utf8Data); hostConnection.sendUTF(JSON.stringify({ msg: command.msg, data: command.data })); } }); controlConnection[uid] = connection; hostConnection.sendUTF(JSON.stringify({ msg: "gamepadAdded", data: uid })); } else { //game not ready, can't connected } } }); return wsServer; };
var serverPort = 9867; // dependencies var webSocketServer = require('websocket').server; var http = require('http'); var players = {}; var nextPlayerId = 0; // create http server var server = http.createServer(function(request, response) { }); server.listen(serverPort, function() { console.log((new Date()) + " Server is listening on port " + serverPort); }); // create websocket server var wServer = new webSocketServer({ httpServer: server }); // connection request callback wServer.on('request', function(request) { var connection = request.accept(null, request.origin); connection.binaryType = "arraybuffer"; var player = {}; player.connection = connection; player.id = nextPlayerId; nextPlayerId++; players[player.id] = player; console.log((new Date()) + ' connect: ' + player.id); // message received callback connection.on('message', function(message) { if (message.type == 'binary' && 'binaryData' in message && message.binaryData instanceof Buffer) { // this works!
} }); } else { response.writeHead(404); response.end(); } }); }); server.listen(1111,function(){ console.log('Http server is listening on port 1111'); }); var socketServer = new socket({ httpServer: server }); var clients = []; socketServer.on('request', function(request){ var connection = request.accept(null, request.origin); var userName = false; var userColor = false; clients.push(connection); function pushToClients(type, message) { var pushObject = { type: type, message: message
var pathname = url.parse(uri).pathname; var querystring = url.parse(uri).query; console.log('pathname: ' + pathname + ", query: " + querystring); if (typeof handlers[pathname] === 'function') { return handlers[pathname](req, res, querystring, clients); } else { console.log('API not defined'); } }); httpServer.listen(8080, '127.0.0.1'); var wsServer = new WebSocketServer({ httpServer: httpServer, autoAcceptConnection: false }); var onWsConnMessage = function(message) { if (message.type === 'utf8') { // Output: {"content":"a"} console.log('Peer message: ' + message.utf8Data); var data = JSON.parse(message.utf8Data); // Real-time data push var obj = { type: 'message', data: { message: data.content,