在 React-Native 方面,我绑定到端口 55555。
import dgram from 'react-native-udp';
import { Buffer } from 'buffer'
const foo = ()=>{
var socket = dgram.createSocket('udp4')
socket.bind(55555, '0.0.0.0', (e)=>{
if(e) console.log(e)
})
socket.once('listening', function() {
var buf = Buffer.from(JSON.stringify('msg'))
socket.send(buf, 0, buf.length, 5000, MACHINE_LOCAL_IP, function(err) {
if (err) alert(err)
console.log('Sent to', MACHINE_LOCAL_IP)
})
})
}
我看到以下控制台日志
socket-0 bound to address: 0.0.0.0 port: 55555
Sent to [...]
它可以按预期工作 8 / 10 次。在我的服务器端,我在 python 中打开一个 UDP 套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(1)
sock.bind(('0.0.0.0', 5000))
while True:
try:
data, in_address = sock.recvfrom(1024)
print(in_address)
except socket.timeout:
pass
except Exception as e:
print(e)
break
当我foo多次运行时,这是我的 python 输出
('192.168.0.5', 55555)
('192.168.0.5', 55555)
('192.168.0.5', 55555)
('192.168.0.5', 55555)
('192.168.0.5', 55555)
('192.168.0.5', 55555)
('192.168.0.5', 52917)
('192.168.0.5', 49619)
('192.168.0.5', 63532)
('192.168.0.5', 55555)
('192.168.0.5', 55555)
我无法弄清楚为什么端口会发生变化!