2

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)

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I's also experiencing this error, for both the IP or localhost. The app is using Expo, so its a different origin, could that be the issue? There is no error, the socket just never fully connects, and keeps retrying.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.