nodejs socket长连接服务端和测试客户端
想用nodejs写个简单的游戏服务器,正在研究中...
服务区代码server.js
var net = require('net'); var HOST = '127.0.0.1'; var PORT = 8080; var chatServer = net.createServer(); var clientList = []; chatServer.on('connection', function(client){ client.name = client.remoteAddress + ':' + client.remotePort; console.log('connect request from ' + client.name) client.setTimeout(5*1000); client.write('Hi!\n'); clientList.push(client); client.on('data', function(data){ broadcast(data, client); }); client.on('end', function(){ clientList.splice(clientList.indexOf(client), 1); }); client.on('close', function() { console.log('close:' + client.name); }); client.on('timeout',function(){ client.end(); }) client.on('error', function(error) { console.log(error); connection.end(); }); }); function broadcast(message, client){ var cleanup = []; for(var i = 1; i < clientList.length; i++){ if(client !== clientList[i]){ if (clientList[i].writable){ clientList[i].write(client.name + ' says:' + message); } else { cleanup.push(clientList[i]); clientList[i].destroy() } } } for (var i = 0; i < cleanup.length; i++) { clientList.splice(clientList.indexOf(cleanup[i]), 1); }; } chatServer.listen(PORT, HOST); console.log('Server listening on ' + HOST +':'+ PORT);
测试客服端代码client.js
var net = require('net'); var HOST = '127.0.0.1'; var PORT = 8080; var client = new net.Socket(); client.connect(PORT, HOST, function(){ console.log('connect to ' + HOST + ':' + PORT); client.write('connet request from ' + + HOST + ':' + PORT + '\n'); client.destroy(); }); client.on('close', function(){ console.log('connetion closed.'); });
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。