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

页面导航:首页 > 网络编程 > JavaScript > nodejs socket长连接服务端和测试客户端

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

来源: 作者: 时间:2016-02-02 09:59 【

想用nodejs写个简单的游戏服务器,正在研究中 服务区代码server jsvar net = require( 39;net 39;);var HOST = 39;127 0 0 1 39;;var PORT = 8080;var chatServer = net createSer

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


 

Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<