Bootstrap

微信小程序UDP通信

微信小程序UDP通信及编码转换

import Encoder  from '../../util/Encoder.js'
onLoad() {
	this.udp = wx.createUDPSocket() //新建udp实例
	this.udp.bind(60000) //udp绑定本机
},
methods: {
    //连接目标
	linkUDP() {
		this.udp.connect({
			address: '192.168.0.87',
			port: 50000,
		})
	},
	//发送信息
	clickUDP() {
		//utf-8转gbk编码
		var gbkArray = Encoder.hexstrToArray(Encoder.stringToGbkHexstr('123哈'));
		console.log("gbkArray>>" , gbkArray)
		let gbk = new ArrayBuffer()
		console.log(gbk)
		
		this.udp.write({
			address: '192.168.0.87',
			port: 50000,
			message: gbk
		})
	},
	//监听接收到的数据
	onUdpMessage: function(res) {
		console.log('收到的信息', res);
		console.log('onUdpMessage() 接收数据 ' + res.remoteInfo.size + ' 字节:' + JSON.stringify(res, null, '\t'));
		// gbk转utf-8
		var x = new Uint8Array(res.message);
		var str = new TextDecoder('gbk').decode(x);
		console.log(str)
	},
},
mounted() {
	//监听收到的数据
	this.udp.onMessage(this.onUdpMessage)
	//监听错误的信息
	this.udp.onError(function(err) {
		console.log(err)
	})
}

参考连接link.
link.

;