如何正确建立UDP Internet连接

时间:2019-05-03 16:43:36

标签: javascript udp

我想建立UDP连接。当服务器的路由器将所有流量转发到本地网络时,下面介绍的代码已在两台不同的计算机上执行。它在python的UDP实现中起作用,在JS之一中似乎不起作用。我尝试了许多路由器的端口转发设置,甚至可以将所有流量从所有地址和端口转发到本地网络,而没有任何结果。 对于该主题的任何帮助,我将不胜感激。

server.js

var PORT = 41986;
var HOST = 'address';
var dgram = require("dgram");

var server = dgram.createSocket("udp6");

server.on("error", function (err) {
  console.log("server error:\n" + err.stack);
  server.close();
});

server.on("message", function (msg, rinfo) {
    var message = msg.toString();
    console.log(message);
    server.send('worked', 0, message.length, rinfo.port, rinfo.address)
});

server.on("listening", function () {
    var address = server.address();
    console.log("server listening " +
      address.address + ":" + address.port);
});

server.bind(PORT, HOST);

client.js

var HOST = 'address';
var REMOTE_PORT = 41986;
var LOCAL_PORT  = 4001;

var dgram = require('dgram');


var client = dgram.createSocket('udp6');
client.bind(LOCAL_PORT);


var header = new Buffer.alloc(8,("Expect:" + 1))
client.send(header, 0, header.length, REMOTE_PORT, HOST,
    function() {
        client.on('message',function(arg) {
            let str = arg.toString();    
            console.log(str);
            clearTimeout(client._connectTimer);
            client.close();
        });
        client._connectTimer = setTimeout(function() {
            client.close();
        }, 1000);
}); 

有关实际上将其发布的Python参考代码。

ipv6client.py

import socket

UDP_IP = "address"  # localhost
UDP_PORT = 41986
MESSAGE = "Hello, World!".encode()

print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)

sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

ipv6server.py

import socket

UDP_IP = "address"
UDP_PORT = 41986

sock = socket.socket(socket.AF_INET6, # Internet
                 socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print("received message:", data)

预期结果是两端正确传输数据。

0 个答案:

没有答案