简体   繁体   中英

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

I am working with a react-native application that involves socket.io. I have installed socket.ion successfully and imported it in my component like:

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:

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. 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. 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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