码迷,mamicode.com
首页 > Web开发 > 详细

nodejs socket长连接服务端和测试客户端

时间:2015-03-20 22:06:32      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:nodejs

想用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.');
});


nodejs socket长连接服务端和测试客户端

标签:nodejs

原文地址:http://blog.csdn.net/xufeng0991/article/details/44497063

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!