var net=require('net');
var host='192.168.0.201';
function executeCommand(socket, command, args) {
var json = {};
switch(command){
case "01":
case "02":
json.beaconid = args;
json.state = command;
result = JSON.stringify(json);
console.log('server:'+result);
socket.write('server:'+result);
cs.write('client:'+result);
break;
}
};
clientList = [];
function broadcast(message, client) {
var cleanup = [];
for(var i=0;i<clientList.length;i++) {
if(client !== clientList[i]) {
if(clientList[i].writable) {
clientList[i].write(message);
} else {
cleanup.push(clientList[i]);
clientList[i].destroy();
}
}
}
for(i=0;i<cleanup.length;i++) {
clientList.splice(clientList.indexOf(cleanup[i]), 1);
}
}
var c = net.createServer(function(socket){
socket.on('data', function(d) {
data = d.toString('utf8').trim();
console.log(data);
broadcast(data, socket);
});
socket.on('end', function() {
console.log('client server disconnected');
try{
clientList.splice(clientList.indexOf(client), 1);
}catch(ex){}
});
socket.on('error', function (ex) {
console.log("client ignoring exception: " + ex);
});
});
c.on('connection', function(client) {
client.name = client.remoteAddress + ':' + client.remotePort
//client.write('Hi ' + client.name + '!\n');
clientList.push(client);
})
c.listen(2222,host);
console.log('client listen on ' + host + ',port:2222...');
var cs = net.connect({port: 2222,host:host});
var s = net.createServer(function(socket) {
console.log('server connected');
socket.on('data', function(d) {
data = d.toString('utf8').trim();
var cmd_re = /^(\d{2})+[ ]*(.*)/g;
cmd_match = cmd_re.exec(data)
if (cmd_match) {
var command = cmd_match[1];
var args = cmd_match[2];
console.log(command+" "+args);
executeCommand(socket, command, args);
}
});
socket.on('end', function() {
console.log('server disconnected');
});
socket.on('error', function (ex) {
console.log("ignoring exception: " + ex);
});
});
s.listen(1111,host);
console.log('server listen on ' + host + ',port:1111...');
Ref:学习 NodeJS 第八天:Socket 通讯