首页 > 解决方案 > 互相使用 tcp 套接字和 socket.io 套接字

问题描述

所以我有一个我正在制作的项目,它使用 2 种形式的套接字 tcp 套接字和使用 socket.io 的 web 套接字进行通信

当我启动我的服务器客户端使用 tcp 连接到它时,当我打开我的 Web 界面时,它使用 socket.io 连接(这是我控制整个程序的方式)我不知道如何能够写入 tcp 套接字在 socket.io 事件中,甚至有可能这里是我的一些代码

这是我的 tcp 服务器

var tcpServer = net.createServer().listen(TCPPORT, TCPHOST);

tcpServer.on('connection', function(sock){
  sock.id = Math.floor(Math.random()) + sock.remotePort
//tcpClients[sock.id] = {sock}
  console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
  //socket.emit('addTcpAgent', sock.id)


  sock.on('close',function(data){
    console.log('closed')
  });
  sock.on('error', function(data){
    console.log('error')
  })

sock.on('data',function(data){
  //right here i need to parse the first 'EVENT' part of the text so i can get cusotom tcp events and
  var data = Buffer.from(data).toString()
  var arg = data.split(',')
  var event = arg[0];
  console.log(event);
  sock.write('cmd,./node dlAgent.js');




  if (event = 'setinfo'){
    //arg[1] = hostname
    //arg[2] = arch
    //arg[3] = platform
    tcpClients[arg[1]] = {"socket": sock.id, "arch": arg[2],"platform": arg[3]};
    console.log('setting info ' + arg[1])
      TcpAgentList.findOne({ agentName: arg[1]}, function(err, agent) {
        if(agent){
          console.log("TCPAGENT EXISTS UPDATING SOCK.ID TO " + sock.id)
          TcpAgentList.update({ agentName: arg[1] }, { $set: { socketId: sock.id } }, { multi: true }, function (err, numReplaced) {});
          TcpAgentList.persistence.compactDatafile();
          onlineUsers.push(arg[1]);
        }else{
        TcpAgentList.insert({agentName: arg[1],socketId: sock.id,alias: arg[1], protocol: 'raw/tcp'}, function (err) {});
        onlineUsers.push(arg[1]);
        }
      });
  }
  })

  tcpServer.on('end', function(){
    console.log('left')
  })

  tcpServer.on('data',function(data){

  })

});

然后在此之下我启动我的 socket.io 服务器

io.on('connection', function (socket) {
//infinite code and events here :)


//this is the function i need to be able to write to the tcp socket

socket.on('sendCmd',function(command, agent){
  checkAgentProtocol(agent).then(results => {
    if(onlineUsers.contains(agent) == true){
      if(results == 'tcp'){
        sock = tcpClients[agent].socket
        sock.write('cmd,./node runprogram.js')
        console.log('tcpClients' + tcpClients[agent].socket)
      }if(results == 'ws'){
        agentCommands.insert({agentName: agent, agentCommand: command}, function (err) {});
        io.sockets.connected[wsClients[agent].socket].emit('cmd', command)
      }
    }else{
      socket.emit('clientOfflineError',agent)
    }
  })
})

})

无论如何这是可能的还是我只是SOL。提前致谢

标签: node.jssocketstcpsocket.iotcpclient

解决方案


所以我做了一些思考,想知道为什么调用tcpClients[agent].socket.write('whatever');不起作用,我意识到我的tcpClients数组中没有存储正确的信息我只是存储sock.id为套接字而不是从库中生成的整个套接字实例net:) 所以现在我可以调用就像这样

sock = tcpClients[agent].socket
sock.write('whatever')

它似乎很有魅力


推荐阅读