主要代码:
console.log( "onLaunch called" ); console.log( "test udp code begin" ); const udp = wx.createUDPSocket(); udp.bind(); udp.send({ address: '写死的IP地址或者域名都不行' , port: 10000, message: 'hello, how are you' }); console.log( "message sent." ); udp.onMessage( function (res) { console.log( "udp.OnMessage res:" , res); let unit8Arr = new Uint8Array(res.message); let encodedString = String.fromCharCode.apply( null , unit8Arr); let message = decodeURIComponent(escape((encodedString))); console.log(message); console.log(res.remoteInfo); that.setData({ receiveMessage: message, fromIp: res.remoteInfo.address }) }); console.log( "test udp code end" ); |
注意我的IP地址是一个外网的服务器的地址,有域名,用域名也不行。我用其他方式尝试往这个地址建立UDP连接是可以成功建立的,排除防火墙之类的问题。
我想问的是,UDP是不是只能局域网发消息?我看有的帖子说是只能和自己在同一个子网段,比如192.168.2.*的话就只能发给192.168.2.*。主要是我看到目前市面上很多的WEBSOCKET库做的游戏,老是断线。TCP的包头确实很大,又不想用HTTP,那样的话包头更大。所以想尝试用UDP直接建立连接。我看有的帖子是UDP直接和服务器建立连接成功了,所以才去写的测试用例的。有人遇到过吗?UDP到底是只能发自己同一子网的,还是可以发任意IP地址?是一定要域名吗?我是测试版,不是发布版,应该不用把域名加到列表里吧?
在mp.weixin.qq.com配置 udp合法域名后就可以了