Usage scenario: When deploying some services and other work in a new Ubuntu server, you need to frequently copy text from the main computer to Ubuntu, but there is no WeChat or VPN, so you can only type letters one by one manually. . So I wanted to write a small program for LAN communication to practice my skills, and later I will see how to implement the web version of LAN communication.
1. Create UDP real column
const udp = wx.createUDPSocket()
2. Bind your own service port (must be of numerical type, each UDP instance requires a port binding, otherwise communication will not be possible)
udp.bind(1234)
3. Monitor the event of starting to monitor packet messages (telling you that it is ready, it means starting monitoring, but not monitoring messages. You must start monitoring, otherwise you will not be able to monitor messages later)
udp.onListening((e) => {
console.log(e);
console.log("开始监听消息");
})
4. Start monitoring messages (this is the reporting of monitoring messages)
udp.onMessage((e) => {
console.log(e);
})
5. Send a message (255.255.255.255 is a broadcast message and can be changed to a specified IP address. The port is filled in with the port of another UDP service. The message format must be a string or numerical type, otherwise it will not be sent and no error will be reported! )
//这就是编码了
const data = JSON.stringify({
ip: "1111",
msg: "哈哈"
})
udp.send({
address: '255.255.255.255',
message: data,
port: 4321
})
6. Parse the reported arrayBuffer format message
The following is decoding. Decoding requires a utf8ArrayToStr.js file. I will paste it at the bottom of the article.
const Utf8ArrayToStr = require('../../utils/utf8ArrayToStr');
const msg = Utf8ArrayToStr(new Uint8Array(res.message))
console.log(msg);
// 结果:{ip: "1111",msg: "哈哈"}