React native and socket.io node not working

后端 未结 4 1166
一向
一向 2021-02-18 21:34

Below is my react native component and node server.js code that I am trying to connect to my node websocket backend.

My react code is running on the same computer as th

相关标签:
4条回答
  • 2021-02-18 22:27

    Your server code seems fine. Though you should check if you can connect to its socket via another client.

    Anyway try this for react native code.

    Import by:

    import io from 'socket.io-client/socket.io'

    In your component do:

    componentDidMount () {
        const socket = io(YOURURL, {
          transports: ['websocket']
        })
    
        socket.on('connect', () => {
          console.log("socket connected")
          socket.emit('YOUR EVENT TO SERVER', {})
          socket.on('EVENT YOU WANNA LISTEN', (r) => {
          })
        })
    
        socket.on('connect_error', (err) => {
          console.log(err)
        })
    
        socket.on('disconnect', () => {
          console.log("Disconnected Socket!")
        })
      }
    
    0 讨论(0)
  • 2021-02-18 22:31

    Also, on your server end, change const websocket = socketio(server) to const websocket = socketio.listen(server);

    0 讨论(0)
  • 2021-02-18 22:35

    I believe it should be

    const io = require('socket.io-client');
    

    Which does work for me.

    I remember running into these sorts of issues when using react native. A lot of socket.io tutorials (including the one on their page) assume you're using an older style of importing JS via script tags in an HTML doc. It looks like socket.io changed the namespace as I do remember it being socket.io-client/socket.io some time ago if memory serves...

    0 讨论(0)
  • 2021-02-18 22:35

    Thanks, Peter. In my opinion, the article you have found isn't helpful because you are trying to connect to the host that serves the page. According to the example on socket.io page, try to make sure that this line works: const io = require('socket.io-client/socket.io'); and connect without link: let socket = io();

    It worked for me, but only in the browser on the same computer. I think when you will test on the device you have to specify your IP instead of localhost.

    Good luck :)

    0 讨论(0)
提交回复
热议问题