Skip to content

Instantly share code, notes, and snippets.

@masa795
Created March 2, 2014 06:53
Show Gist options
  • Save masa795/9302929 to your computer and use it in GitHub Desktop.
Save masa795/9302929 to your computer and use it in GitHub Desktop.
Node.jsサンプル
var WebSocket = require('websocket').server,
Http = require('http'),
Config = require('config');
console.log("========= Start ===========");
console.log(new Date());
console.log("NODE_ENV="+process.env.NODE_ENV);
console.log("NODE_PATH="+process.env.NODE_PATH);
console.log("port="+Config.websocket.port);
console.log("=================================");
var connectWebSockets = {};
var accessHeader = null;
var main = function() {
var createMain = function(port) {
return function() {
var HttpServer = Http.createServer(httpHandler);
HttpServer.listen(port);
var ws = new WebSocket({
httpServer: HttpServer,
autoAcceptConnections:true
});
ws.on('connect',webSocketConnectHandler);
HttpServer.on('upgrade', function(req, socket, head) {
console.log("HttpServer upgrade.");
accessHeader = req.headers;
});
};
};
var main1 = createMain(Config.websocket.port);
main1();
};
var httpHandler = function(req,res) {
console.log('httpHandler access.' + req.url);
res.writeHead(200,{"Content-Type": 'text/plain'});
res.write('Node HTTP Access.');
res.end();
};
var webSocketConnectHandler = function(con) {
var from = null;
var to = null;
con.on('upgrade', function(req, socket, head) {
console.log("webSocketConnectHandler upgrade.");
console.log(req);
});
con.on('message', function(data)
{
console.log("webSocketConnectHandler message.");
console.log("from="+ from + " to="+to + " data.utf8Data="+data.utf8Data);
var packet;
try
{
packet = JSON.parse(data.utf8Data);
}catch(ex)
{
console.log("json Parse Error. " + data.utf8Data );
return;
}
var currentFrom = packet['from'];
var currentTo = packet['to'];
var type = packet['type'];
if(currentFrom == "")
{
return;
}
if (from == null) {
from = currentFrom;
}
connectWebSockets[from] = con;
to = currentTo ;
var relayTo = connectWebSockets[to];
var ret = '';
try
{
ret = JSON.parse(data.utf8Data);
ret["serverTime"] = new Date();
var json_text = JSON.stringify(ret);
}catch(ex)
{
console.log("Json Parse Error . " + data.utf8Data );
return;
}
console.log("return json_text="+json_text);
relayTo.send(json_text);
});
con.on('close',function(code, desc) {
console.log("webSocketConnectHandler close.");
delete connectWebSockets[from];
console.log("close. code="+code+" desc=" + desc + " from="+from+" to="+to);
});
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment