反应本机Web套接字连接转到任何其他组件时关闭。如何设置Web套接字连接始终处于打开状态?

时间:2018-07-24 21:09:31

标签: reactjs react-native websocket

我正在使用本机背景地理定位,并在allow为true时获取位置。然后我正在建立与Web套接字的连接并发送一些数据。但是我也使用react-navigation,当我移到另一个屏幕时,连接已关闭,并且不将数据发送到服务器。但是我想在获取位置后始终保持websocket连接。该怎么做?

我正在搜索任何相关文章,但一无所获?

SlicerItem

导航

    class TripStartStopScreen extends React.Component {
      constructor(props) {
        super(props);
        this.state = {}
      }
      componentDidMount() {
       BackgroundGeolocation.on("location", location => {
      this.setState({
        current_loc_long: location.longitude,
        current_loc_lat: location.latitude
      });

      console.log("need trip id ---->", this.props);

      location.order_id = this.props.tripdata.TRIPIDREDUCER.tripid;

      console.log(location.order_id);

      var Time = new Date(location.time);

      var UTC = Time.setHours(Time.getHours() - 6);

      console.log(UTC);

      var formatedDate = moment(UTC).format("YYYY-MM-DD hh:mm A");

      location.time = formatedDate;

      console.log(location.time);

      console.log("[DEBUG] BackgroundGeolocation location", location);

      // this.ws.send(JSON.stringify(location));

      //this.props.dispatch(SendToServer(location, this.props.tripdata.TRIPIDREDUCER.tripid))

      function connect() {
        var ws = new WebSocket("ws://96.126.100.12:8754");
        ws.onopen = function() {
          // subscribe to some channels
          ws.send(JSON.stringify(location));
        };

        ws.onmessage = function(e) {
          console.log("Message:", e.data);
        };

        ws.onclose = function(e) {
          Alert.alert("Connection Closed");
          setTimeout(function() {
            connect();
          }, 1000);
        };

        ws.onerror = function(err) {
          Alert.alert("Connection Error");
          console.error(
            "Socket encountered error: ",
            err.message,
            "Closing socket"
          );
          ws.close();
        };
      }

      connect();

      Alert.alert("Trip Started");

      if (this.state.status == false) {
        this.state.offline_Data.push(location);
      }
    });

    BackgroundGeolocation.checkStatus(status => {
      console.log(
        "[INFO] BackgroundGeolocation service is running",
        status.isRunning
      );
      console.log(
        "[INFO] BackgroundGeolocation service is enabled",
        status.locationServicesEnabled
      );
      this.setState({
        isRunning: status.isRunning,
        isLocationOn: status.locationServicesEnabled
      });
    });
  }

  componentWillUnmount() {
    BackgroundGeolocation.events.forEach(event =>
      BackgroundGeolocation.removeAllListeners(event)
    );

    NetInfo.isConnected.removeEventListener(
      "connectionChange",
      this.handleConnectionChange
    );
  }


  }

0 个答案:

没有答案