最近做rn項目中做到通訊模塊筷弦,需要app端與硬件進行通訊杭朱,正常的通訊用的都是websocket饱须,但是當app端ip變化的時候域醇,需要app進行廣播告知硬件進行相應的改變,這個時候就需要用到upd廣播。我們這里用到的是這個庫:[react-native-udp](https://github.com/tradle/react-native-udp
)
1. 首先 引入庫
npm install --save react-native-udp
2.和原生進行鏈接
react-native link react-native-udp
# OR, if you're using react-native older than 0.31:
rnpm link react-native-udp
3配置原生模塊
- Register and load the Native Module in your Main application (import, getPackages)
import com.tradle.react.UdpSocketsModule; // <--- import //
public class MainApplication extends Application implements ReactApplication {
...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new UdpSocketsModule() // <- add here //
);
}
}
- package.json
only if you want to write require('dgram') in your javascript
{
"browser": {
"dgram": "react-native-udp"
}
}
3.rn部分
import dgram from 'react-native-udp';
import { udpPort } from '../config';
const toByteArray = obj => {
var uint = new Uint8Array(obj.length);
for (let i = 0, l = obj.length; i < l; i++) {
uint[i] = obj.charCodeAt(i);
}
return new Uint8Array(uint);
}
export const sendUdpMessage = async (bCast, message) => {
let socket = dgram.createSocket('udp4')
const buf = toByteArray(JSON.stringify(message))
socket.send(buf, 0, buf.length, udpPort, bCast, err => {
if (err) {
alert('error')
socket && socket.close()
// TODO: 錯誤處理
return
}
socket && socket.close()
alert('message was sent')
})
}
4. 寫一個簡單的js 文件 node端進行測聯(lián)調譬挚。
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("error", function (err) {
console.log("server error:\n" + err.stack);
server.close();
});
server.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " +
rinfo.address + ":" + rinfo.port);
});
server.on("listening", function () {
var address = server.address();
console.log("server listening " +
address.address + ":" + address.port);
});
server.bind(12347);