20

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 the server. I have found so many varying answers on here, and github, none of which I can get working.

I also found this question which was never answered, and this question has an answer, which I cannot get working (was asked over a year ago)

I have found this article and tried to amend my code based on these guidelines but this did not work.

react code

import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';

const io = require('socket.io-client/socket.io');
let socket = io('http://localhost:3000');

export default class App extends React.Component {

    constructor(props) {
        super(props);
        console.log(socket);
    }

    render() {
        return (
            <View>
                <Text>Websocket</Text>
            </View>
        );
    }
}

server.js

const express = require('express');
const http = require('http')
const socketio = require('socket.io');

const app = express();
const server = http.Server(app);
const websocket = socketio(server);
server.listen(3000, () => console.log('listening on *:3000'));

console.log(websocket)

// The event will be called when a client is connected.
websocket.on('connection', (socket) => {
  console.log('A client just joined on', socket.id);
});

I am using the following versions of packages

"expo": "^16.0.0",
"react": "16.0.0-alpha.6",
"react-native": "^0.43.4",
"socket.io-client": "^1.7.3"
5
  • The article you linked to said to use require rather than import for the socket.io library. Did you try that? Commented May 3, 2017 at 4:45
  • Side question, I just used the built-in web socket library for React Native this past weekend for the first time. It seemed ok but it was my first time using web sockets. What advantage does the socket.io library give over the native library? Commented May 3, 2017 at 4:46
  • See my answer below. Commented May 9, 2017 at 0:37
  • Have you tried using the ip address for localhost instead like: let socket = io('127.0.0.1:3000'); Commented Jan 2, 2018 at 17:55
  • please be adviced you should use your ip adress since you are connecting from another machine, android emulator in this case, ip must be something that normally starts with 192.168.1.52 Commented Mar 24, 2019 at 7:28

5 Answers 5

7
+25

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

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

2 Comments

Why is it a require and not an import? Why is there a difference?
You could use import if you want to. The difference between my answer and OP is socket.io-client vs socket.io-client/socket.io.
6

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!")
    })
  }

4 Comments

I have it set up like this and it's working fine...only difference is I'm importing like this import io from 'socket.io-client';
Oh that's great to hear. There could be namespace differences depending on the version of socket io. The code above should work as long as you can get the io function
transports: ['websocket'] this was a life saver for me!!! Thanks a lot!
Great! Dude who posted question never bothered choosing the right answer.
0

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

Comments

0

When you use localhost (127.0.0.1) in your React Native app running on an Android emulator, it's referring to the emulator itself — not your actual machine where the NestJS server is running.

The Android emulator runs in a virtual machine. It has its own internal network, so localhost points to the emulator's own environment, not your computer.

Try this:

const socket = io('http://10.0.2.2:3001', { transports: ['websocket'] });

Comments

-1

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 :)

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.