用nodejs编写UDP服务端,uniapp开发安卓APP客户端UDP 服务端效果图: 客户端效果图: UDP广播服务端 nodejs 代码:
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('close',()=>{
console.log('socket已关闭');
});
server.on('error',(err)=>{
console.log(err);
});
server.on('listening',()=>{
console.log('socket正在监听中...');
server.setBroadcast(true);
server.setTTL(128);
});
server.on('message',(msg,rinfo)=>{
console.log(`receive message from ${rinfo.address}:${rinfo.port}`);
var newtopic = new Buffer.from(msg,"utf-8").toString();
console.log(newtopic)
server.send('Hi Client',8061,'192.168.1.255');
});
server.bind('8060','192.168.1.196');
UDP广播客户端 uniapp源码:
var DatagramPacket = plus.android.importClass('java.net.DatagramPacket');
var DatagramSocket = plus.android.importClass('java.net.DatagramSocket');
var InetAddress = plus.android.importClass('java.net.InetAddress');
var NetworkInterface = plus.android.importClass('java.net.NetworkInterface');
var JString = plus.android.importClass('java.lang.String');
var socket;
var port = 8060;
var getPort = 8061;
var timeout = 6000;
try {
if (DatagramSocket == undefined) {
return;
}
var ip = InetAddress.getByName("192.168.1.255");
socket = new DatagramSocket(getPort);
socket.setSoTimeout(timeout);
var sendData = Array.prototype.slice.call((new Buffer(`hello server`)), 0);
var sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
console.log('广播地址:'+ip.getHostAddress(), '端口号:'+sendPacket.getPort())
socket.send(sendPacket);
var isReceive = true;
while (isReceive) {
try {
var buffer = new Array(1024).fill(0);
var packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
var data = new JString(packet.getData()).trim();
if (data.length == 0) {
isReceive = false;
} else {
console.log('=====收到数据======', data);
}
} catch (ex) {
socket.close();
isReceive = false;
console.log('接收数据失败')
}
}
} catch (ex) {
console.log('========出错了=======', ex);
} finally {
if (socket != undefined) {
socket.close();
}
}
参考文章:https://my.oschina.net/u/4004226/blog/5125863
|