gpt4 book ai didi

sockets - 如何使用NodeJS将监听一个端口的WebSocket连接到监听另一个端口的Net socket?

转载 作者:行者123 更新时间:2023-12-03 12:02:35 26 4
gpt4 key购买 nike

这是我尝试但不起作用的方法。我可以将传入的消息从WebSocket连接转发到NetSocket,但是只有NetSocket收到的第一个消息才到达WebSocket后面的客户端。

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const NetSocket = require('net');
const net = new NetSocket.Socket();

// Web socket
wss.on('connection', function connection(ws) {
console.log((new Date()) + ' Remote connection accepted ' + ws.remoteAddress);
ws.on('message', function incoming(message) {
console.log('Received from remote: %s', message);
net.write(message)
});

ws.on('close', function(){
console.log((new Date()) + ' Remote connection closed');
});
});


// Net socket
net.connect(8745, '127.0.0.1', function() {
console.log((new Date()) + ' Local connection accepted');
});

net.on('data', function(data) {
console.log('Received from local: ' + data);
// Iterate the connected devices to send the broadcast
wss.clients.forEach(function each(c) {
if (c.readyState === WebSocket.OPEN) {
c.send(data);
}
});
});

net.on('close', function() {
console.log('Local connection closed');
});

最佳答案

经过新的研究,我发现问题出在我的快速代码中。

private func setReceiveHandler() {
webSocketTask.receive { result in
defer { self.setReceiveHandler() } // I was missing this line
do {
let message = try result.get()
switch message {
case let .string(text):
print("Received text message: \(text)")
case let .data(data):

因此,只需将 defer {self.setReceiveHandler()} 添加到我的函数中,它便开始工作。

Note the defer statement at the start of the receive handler. It calls self.setReceiveHandler() to reset the receive handler on the socket connection to allow it to receive the next message. Currently, the receive handler you set on a socket connection is only called once, rather than every time a message is received. By using a defer statement, you make sure that self.setReceiveHandler is always called before exiting the scope of the receive handler, which makes sure that you always receive the next message from your socket connection.



我从以下方面获得了信息:

https://www.donnywals.com/real-time-data-exchange-using-web-sockets-in-ios-13/

关于sockets - 如何使用NodeJS将监听一个端口的WebSocket连接到监听另一个端口的Net socket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62455701/

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