简体   繁体   中英

socket.io is not able to connect react-native and nodejs

I am trying to establish websocket connection between nodejs and react-native. But unfortunately it is not working.

The issue is that client side do not get connected with server via sockets.

Here is nodejs (server-side) code

const express = require('express');
const app = express();

var server = app.listen(3000, () => console.log('server connected'))
const io = require("socket.io")(server)

io.on("connect", (socket) => {
  console.log("user connected");
  socket.on("chat message", mssg => {
    console.log(mssg);
    io.emit("chat message", mssg)
  })
})


app.get('/', (req, res) => {
  res.send("Hey! u are connected to server");
})

Here is react-native(client-side) code

import React from 'react'
import { Button } from 'react-native'
import io from 'socket.io-client'

export default class extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.socket = io("http://localhost:3000");
    this.socket.on('connect', () => console.log("connected"))
    this.socket.on("chat message", mssg => {
      console.log("mssg recieved in client:", mssg)
    })
  }
  render() {
    return <Button title="click to send message" onPress={() => {
      this.socket.emit("chat message", "anshika this side")
    }
    } />
  }
}

Libraries used : react-native version:0.62.1, socket.io-client version:2.3.0 (client-side), socket.io version:2.3.0 (server-side)

I solved the issue by adding ip address of my laptop instead of putting localhost as a link in react-native code

you must use your ipv4 address and the catch was to specify "transports" parameters in io as ['websocket'] what's no needed in web apps

import io from 'socket.io-client'

io('http://xxx.xxx.x.xxx:port', {
   transports: ['websocket']
})

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