react-native端 udp通讯

最近做rn项目中做到通讯模块,需要app端与硬件进行通讯,正常的通讯用的都是websocket,但是当app端ip变化的时候,需要app进行广播告知硬件进行相应的改变,这个时候就需要用到upd广播。我们这里用到的是这个库:react-native-udp

)

1. 首先 引入库

1
npm install --save react-native-udp

2.和原生进行链接

1
2
3
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)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    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

    1
    2
    3
    4
    5
    {
    "browser": {
    "dgram": "react-native-udp"
    }
    }

3.rn部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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端进行测联调。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 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);