我使用的技术栈是:react-native(0.56.0)+ react-navigation + react-redux + ant-design + axios
我在做的ReactNative项目需要实现同一WIFI下跨平台互传文件功能,涉及原生模块的功能
我实现这两个功能使用的库有
首先需要明白限制条件是在同一个局域网内(连接同一wifi),前期已经用umi开发了一组传输文件时准备在PC上展示的相关网页并打包出来。
核心技术:
通过使用NanoHTTPD在手机上建立本地服务器实现数据传输。
为了保证安全性,需要PC端输入APP生成的验证码予以验证。
整体流程:
1. 判断是否连接WIFI并获取ip地址
WifiManager是 Android 暴露给开发者使用的一个系统服务管理类, 其中包含对WiFi的响应的操作函数。
//获取wifi服务
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
if (!wifiManager.isWifiEnabled()) {
return null;
}
//判断wifi是否连接
if (wifiManager.getConnectionInfo() == null) {
return null;
}
// ip地址获取
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
return (ipAddress & 0xFF) + "." +
((ipAddress >> 8) & 0xFF) + "." +
((ipAddress >> 16) & 0xFF) + "." +
(ipAddress >> 24 & 0xFF);
2. 启动服务
主要逻辑继承NanoHTTPD,根据你的需求重写serve方法就可以了
在我写的this.openHttp(port,code,mainKey,toPage)中,code是验证码,mainkey是自定义需要传输的部分内容,toPage是判断是由手机向PC还是PC向手机传输文件。
// 随机数防止端口被占用,如果被占用catch后stopServer
int port = (int)((Math.random()*9+1)*1000);
final String host = ip + ":" + port;
this.openHttp(port,code,mainKey,toPage);
promise.resolve("http://" + host);
//
private void openHttp(int port,String code,ReadableMap mainKey, String toPage) throws IOException {
httpServer = new HttpServer(getReactApplicationContext(), port,code,mainKey,toPage);
httpServer.start();
}
3. 自定义的serve,返回网页或者响应请求
根据不同的路径返回不同的数据
将文件转化的字符串或者数组作为响应内容返回return Response.newFixedLengthResponse(字符串)
或者return Response.newFixedLengthResponse(状态码,mime类型,字节数组)
public Response serve(IHTTPSession session){
String uri = session.getUri();
// 根据html的路径返回相应的操作
if (uri.equals("/postValidatePhoneCode")) {
return validatecode(session);
}else if (uri.equals("/upload")){
return renderUpload(session);
}else if (uri.equals(