简体   繁体   English

React-native socket.io发射/不触发动作

[英]React-native socket.io emit / on actions not firing

I am working with a react-native application that involves socket.io. 我正在使用一个涉及socket.io的React-native应用程序。 I have installed socket.ion successfully and imported it in my component like: 我已经成功安装了socket.ion并将其导入到我的组件中,例如:

import React, { Component } from 'react';
import io from 'socket.io-client/dist/socket.io';
const connectionConfig = {
    jsonp: false,
    reconnection: true,
    reconnectionDelay: 100,
    reconnectionAttempts: 100000/// you need to explicitly tell it to use websockets
  };
  socket = io('http://192.168.1.100:3001', connectionConfig);
type Props = {};
export default class Socket extends Component<Props> {
    constructor(){
    super();
    socket.emit("Button",'pressed')
    socket.on('userid',(id)=>{
      this.setState({userid:{id}});
      Alert.alert(id);
    })
  }

And the code for my server side using express is: 服务器端使用express的代码是:

io.on('connection', function(socket){
  console.log(socket.id);
  socket.on('Button',function(data){
    console.log("ButtonPressed");
  });
 socket.emit('userid',socket.id);

}) What is strange, after like every 1.5s the server console logs a different socket.id when i ran the application on an android device. })奇怪的是,每隔1.5秒,当我在Android设备上运行应用程序时,服务器控制台就会记录一个不同的socket.id。 I assume the socket.io connects successfully but again disconnects in the 1.5si mentioned such that the socket.emit and socket.on event don't get to be executed.I have tried many options provided but cannot get the right way to fix this. 我假设socket.io连接成功,但是在提到的1.5si中再次断开连接,这样就不会执行socket.emit和socket.on事件了。我尝试了提供的许多选项,但无法找到正确的方法来解决。 Please if you know a work-around i highly appreciate. 如果您知道解决方法,请多多关照。 Thank you. 谢谢。

I realised on android if you use the option transports: ['websocket'] and you are in the development mode, then first enable the debug remotely by shaking your phone and sockets will work fine for you. 我在android上意识到,如果您使用以下选项传输:['websocket']并且您处于开发模式,则首先通过摇动手机远程启用调试,插座将对您正常工作。 So basiclly you should have something like 所以基本上你应该有类似

   import io from 'socket.io-client';
const connectionConfig = {
    jsonp: false,
    reconnection: true,
    reconnectionDelay: 100,
    reconnectionAttempts: 5000,
    transports: ['websocket']/// you need to explicitly tell it to use websockets
  };
  socket = io('http://192.168.1.100:3001', connectionConfig);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM