Expo和React Native OBD2 Wifi使用WebSocket连接

vfhzx4xs  于 2023-08-05  发布在  React
关注(0)|答案(1)|浏览(127)

我买了一个通用的obd 2 wifi阅读器,与应用商店的其他应用程序配合使用效果很好。我已确认IP和端口为:192.168.0.10和35000使用所述应用。我想使用Expo和React Native构建一个简单的HUD移动的应用程序,因为我没有Apple开发者许可证,所以我喜欢使用Expo,因为它易于使用。iPhone是我的日常驱动程序。
现在我试图建立连接,连接总是挂起,没有回调被调用...几分钟后,我在onerror上收到以下消息(超时):无法完成操作。套接字未连接。出于测试目的,我还下载并运行了以下repo:https://github.com/ezobd/sim这样我就不用去车里测试了。但是当我尝试连接到这个时,我实际上很快得到了一个onError回调,并显示以下消息:“Sec-WebSocket-Accept响应无效”。服务器只输出/GET的头文件,其他什么都不输出。我的印象是,使用这种方法将工作,但它不...我将分享当用户按下按钮时调用的connect函数的代码:

const connect = () => {
    if(connectionStatus === 'disconnected') {
      setConnectionStatus('connecting');
      const newWs = new WebSocket(`ws://${ip}:${port}`, "tcp"); // also tried without the "tcp" protocol
      const currentTime = new Date().getTime();
      newWs.onopen = () => {
        console.log("ws opened");
        Alert.alert("Connection established in " + (new Date().getTime() - currentTime) + "ms");
        setWs(newWs); // Update the value of ws using setWs
        setConnectionStatus('connected');
      };
      newWs.onmessage = (e) => {
        // A message was received
        console.log(e.data);
        Alert.alert("Message received: " + e.data);
      };
      newWs.onerror = (e) => {
        // An error occurred
        console.log(e);
        setConnectionStatus('disconnected');
        Alert.alert("Connection failed with error " + e.message);
      };
      newWs.onclose = () => {
        console.log("ws closed");
        setConnectionStatus('disconnected');
        Alert.alert("Connection closed");
      };
    }
    else {
      Alert.alert("Connection is already being established");
    }
  };

字符串
我的repo如下:https://github.com/bearkillerPT/obd2-speedometer-wifi提前感谢!

nbewdwxp

nbewdwxp1#

此obd服务器不是为处理WebSocket连接而设计的,这就是为什么当您尝试使用WebSocket连接时会看到HTTP GET请求的原因。
WebSockets和TCP套接字是不同的。WebSocket连接以HTTP握手开始,该握手升级为WebSocket连接。对于原始TCP套接字连接,情况并非如此,这是您的服务器所期望的。
如果你想从你的React Native应用连接到这个服务器,你应该使用TCP套接字连接,而不是WebSocket连接。不幸的是,React Native不支持开箱即用的原始TCP套接字连接。
有一些库可以将此功能添加到React Native,例如react-native-tcp。您可以使用此库创建从React Native应用到服务器的TCP套接字连接。Expo不支持这个库,所以它不能解决我的问题。我知道,如果你有一台运行macOS >= 13的Mac,你可以将应用程序编译成一个.ipa文件,而不需要签名。我讨厌苹果。

相关问题