Created
August 25, 2013 09:55
-
-
Save deamondz/6333058 to your computer and use it in GitHub Desktop.
Server.js for node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var http = require('http'), | |
| fs = require( "fs" ); | |
| //HTTP part | |
| var htmlTemplate = fs.readFileSync( | |
| (__dirname + "/index.htm"), | |
| "utf8" | |
| ), | |
| server = http.createServer(function(req, res){ | |
| res.writeHead(200,{ 'Content-Type': 'text/html' }); | |
| //res.end(htmlTemplate); | |
| res.end(); | |
| }); | |
| server.listen(8080); | |
| // Socket part | |
| var WebSocketServer = require('ws').Server, | |
| wss = new WebSocketServer({port: 1337}), | |
| clients = {}; | |
| wss.on('connection', function(ws) { | |
| var id; | |
| ws.on('message', function(message) { | |
| //console.log('получено сообщение ' + message); | |
| msg = JSON.parse(message); | |
| if('gid' in msg){ | |
| id = msg.gid; | |
| clients[id] = ws; | |
| for(var key in clients) { | |
| clients[key].send(message); | |
| } | |
| } | |
| }); | |
| ws.on('close', function() { | |
| console.log('соединение закрыто ' + id); | |
| if(id) delete clients[id]; | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment