Anshika Agrawal
Anshika Agrawal

Reputation: 139

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)

Upvotes: 2

Views: 1727

Answers (2)

kuubson
kuubson

Reputation: 189

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']
})

Upvotes: 0

Anshika Agrawal
Anshika Agrawal

Reputation: 139

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

Upvotes: 3

Related Questions