gpt4 book ai didi

javascript - 获取有关数据响应的 TCP 套接字特定数据

转载 作者:行者123 更新时间:2023-11-30 13:49:43 25 4
gpt4 key购买 nike

我编写了以下函数:

  let responses = {}
let socks = {}
module.ping = function (port, address) {
//console.log(`Ping function was called - ${address} ${port}`)
if (socks[`${address}:${port}`]) {
//console.log("Using existing socket")
responses[`${address}:${port}`] = false
sock = socks[`${address}:${port}`]
sock.write('PING\n')
console.log(`Sent PING to ${address} ${port}`)
}
else {
sock = new net.Socket();
responses[`${address}:${port}`] = false
sock.connect(port, address, async function() {
sock.write('PING\n')
console.log(`Sent PING to ${address} ${port}`)
});

// Response listeners
sock.on('data', function(data) {
clean_data = data.toString().replace(/\n/g, '').replace(/\r/g, '')
console.log(`[${sock.remoteAddress}:${sock.remotePort}] Received ${clean_data}`)
if (clean_data == 'PONG') {
//console.log(`[${sock.remoteAddress}:${sock.remotePort}] Received PONG`)
//sock.end()
//delete socks[`${address}:${port}`]
responses[`${sock.remoteAddress}:${sock.remotePort}`] = true
}
}
});
sock.on('error', function(error) {
if (sock.remoteAddress) {
responses[`${sock.remoteAddress}:${sock.remotePort}`] = false
}
sock.destroy()
delete socks[`${address}:${port}`]
});

// Add to list of sockets
if (sock) {
socks[`${address}:${port}`] = sock
}
}
}

在另一端,我有一个监听 TCP 服务器,它简单地响应“PONG\n”。当我尝试单个主机时,我得到了预期的输出:

module.ping(1337, 10.0.0.100)
await delay(5000) // Custom function
module.ping(1337, 10.0.0.100)

Sent PING to 10.0.0.100 1337

[10.0.0.100:1337] Received PONG

Sent PING to 10.0.0.100 1337

[10.0.0.100:1337] Received PONG

但是,当我尝试攻击多个主机时:

module.ping(1337, 10.0.0.100)
module.ping(1337, 10.0.0.200)
await delay(5000) // Custom function
module.ping(1337, 10.0.0.100)
module.ping(1337, 10.0.0.200)

Sent PING to 10.0.0.100 1337

Sent PING to 10.0.0.200 1337

[10.0.0.200:1337] Received PONG

[10.0.0.200:1337] Received PONG

Sent PING to 10.0.0.100 1337

Sent PING to 10.0.0.200 1337

[10.0.0.200:1337] Received PONG

[10.0.0.200:1337] Received PONG

在我看来,我添加的“数据”事件监听器以某种方式绑定(bind)到我的代码中的错误地址,但我看不到位置。如果我向列表中添加更多主机,最后发送 PING 的主机就是所有 PONG 都被标记为其中一部分的主机。

最佳答案

对于初学者,我没有看到 sock 变量的声明,这意味着它在某个更高的范围内,并且在正在进行的不同异步操作之间被错误地混淆或打败了。

在本地声明该变量,这样每次使用它都是一个单独的变量,并且一个异步操作不会覆盖您用于另一操作的那个。必须在本地声明所有并非特意用于更高范围和共享的变量。

我不知道这是否是这里唯一的问题,但它确实是一个问题。例如,如果您连续两次调用 .ping() 并且必须创建两个新套接字,则第二个套接字将覆盖 之前的 sock 变量。 connect() 成功导致您将 PING 发送到错误的 sock,这正是您的诊断日志所显示的。

关于javascript - 获取有关数据响应的 TCP 套接字特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58515040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com