tcp客户端服务器通信

时间:2015-08-08 17:44:37

标签: node.js tcp

我正在尝试构建TCP服务器/客户端聊天 到目前为止,我的代码是

server.js

var net=require("net");
var sockets=[];
var server=net.createServer(function(socket){
    console.log("new socket connected");
    sockets.push(socket);
    var sh="";
    socket.on("data",function(data){
        sh=sh+data;
    });
    socket.on("end",function(){
        sockets.forEach(function(x){
            if(x!==socket){
                x.write("Dakto poveda :"+ sh);
                sh="";
            }
        });
    })
    socket.on("close",function(){
        console.log("Connection closed")
    })
}).listen(8888)

和client.js

var net=require("net");
var client= new net.Socket();
client.connect(8888,function(){
    console.log("Conncted");
    client.write("Hello from client")
});
client.on("data",function(data){
    console.log("data "+data)
});
client.on("close",function(){
    console.log("Client closed");
    client.write("client closed")
})

我启动server.js然后我打开新的cmds并在其中启动client.js。在客户端连接的写入服务器cmd中,在客户端cmd中写入" connected"它并没有写出来自客户的问候" +问题是,我如何在这些客户端/服务器之间进行通信?当我启动这些文件时,我不能再写入cmd了

1 个答案:

答案 0 :(得分:1)

目前,在将缓冲数据显示到stdout之前,您的服务器代码会一直等到客户端断开连接。如果您想立即显示它,您将需要使用某种框架协议,以便您知道何时发送消息"开始和结束。一种流行的方法是使用换行符分隔的JSON消息。例如:

server.js

var net = require('net');
var sockets = [];
function broadcast(from, msg) {
  msg = JSON.stringify('Dakto poveda: ' + msg) + '\n';
  sockets.forEach(function(x) {
    if (x !== from)
      x.write(msg);
  });
}
var server = net.createServer(function(socket){
  sockets.push(socket);

  var buffer = '';
  socket.on('data',function(data) {
    buffer += data;
    var idx;
    while ((idx = buffer.indexOf('\n')) > -1) {
      broadcast(socket, JSON.parse(buffer.slice(0, idx)));
      buffer = buffer.slice(idx + 1);
    }
  });

  socket.on('close',function() {
    // Remove dead socket from list
    sockets.splice(sockets.indexOf(socket), 1);

    console.log('Connection closed')
  });
}).listen(8888);

client.js

var net = require('net');
var client = new net.Socket();
function send(msg) {
  client.write(JSON.stringify(msg) + '\n');
}
client.connect(8888, function() {
  console.log('Conncted');
  send('Hello from client');
});
var buffer = '';
client.on('data', function(data) {
  buffer += data;
  var idx;
  while ((idx = buffer.indexOf('\n')) > -1) {
    console.log('message received: ' + JSON.parse(buffer.slice(0, idx)));
    buffer = buffer.slice(idx + 1);
  }
});
client.on('close',function(){
  console.log('Client closed');
});

如果您想在邮件中嵌入换行符等,那么JSON转换会非常有用,否则会破坏您的邮件框架。另一个好处是你可以发送JavaScript对象,数组等,而不仅仅是简单的字符串。这样可以更轻松地传递不同类型的数据。