所以我有一个我正在做的项目,它使用两种形式的套接字进行通信TCP套接字和使用套接字的Web套接字。
当我启动服务器时,客户机使用TCP连接到它,当我打开Web界面时,它使用socket.io连接(这是我控制整个程序的方式)
我不知道如何在socket.io事件中写入TCP套接字,这里是否可能有我的一些代码
这是我的TCP服务器
var tcpServer = net.createServer().listen(TCPPORT, TCPHOST);
tcpServer.on('connection', function(sock){
sock.id = Math.floor(Math.random()) + sock.remotePort
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
sock.on('close',function(data){
console.log('closed')
});
sock.on('error', function(data){
console.log('error')
})
sock.on('data',function(data){
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'){
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) {
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)
}
})
})
})
不管怎样,这是可能的还是我只是索尔。提前谢谢