Why my socketio is not connecting with my socketio-client?

Viewed 65

i am working on a chatapp project that needs a real time chatting so i have used socketio in my server side which is written in nodejs and than used socketio-client in my main chatapp react-native project.

But now a problem is coming my socket is not initializing. I'm not able to connect my server with my main app. I am using socketio and socketio client my both the socket version are same 4.5.1 but it's not even connecting. I have tried to use old version of socket but its also not working and I have also tried to change my localhost port to 4000 but it's also not working.

My server code:

const express = require('express');
var bodyParser = require('body-parser');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const port = process.env.PORT || 3000;

require('./src/config/database')
const user_routes = require('./src/user/users.routes');


app.use(bodyParser.urlencoded({extended: true}))
app.use(express.json())

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.use('/User', user_routes)
io.on('connection', (socket) => {
  console.log('a user connected');


  socket.on('send_message',(data)=>{
    console.log("received message in server side",data)
    io.emit('received_message',data)
  })

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
  
});

server.listen(port, () => {
  console.log( `Server running at http://localhost:${port}/`);
});

My app socketservice file code:

import io from 'socket.io-client';

const SOCKET_URL = 'http://localhost:3000'

class WSService {

    initializeSocket = async () => {
        try {

            this.socket = io(SOCKET_URL, {
                transports: ['websocket']
            })
            console.log("initializing socket", this.socket)

            this.socket.on('connect', (data) => {
                console.log("=== socket connected ====")
            })

            this.socket.on('disconnect', (data) => {
                console.log("=== socket disconnected ====")
            })

            this.socket.on('error', (data) => {
                console.log("socekt error", data)
            })

        } catch (error) {
            console.log("scoket is not inialized", error)
        }
    }

    emit(event, data = {}) {
        this.socket.emit(event, data)
    }
    
    on(event, cb) {
        this.socket.on(event, cb)
    }

    removeListener(listenerName) {
        this.socket.removeListener(listenerName)
    }

}

const socketServcies = new WSService()

export default socketServcies

Where I have marked it should be connected = true but it's false in the dev console I have done console log so check that it's connecting or not and I can see that it's not connecting. How to make it connect?

There is no error in my app or server I have checked many times and my server is also running when I am running my app.

3 Answers

Answering my own question The problem was i was using android emulator and android in an emulator can't connect to localhost you need to use the proxy ip so when i add http://10.0.2.2:3000 in const SOCKET_URL = 'http://10.0.2.2:3000' than its working fine credit goes to gorbypark who told me this in discord

I'm assuming that your front and back runs in localhost. The documentation says that if the front-end is in the same domain as the back-end, you don't need to use the URL. Since you have the options parameter declared, you can use the default argument window.location in first place:

class WSService {

    initializeSocket = async () => {
        try {

            this.socket = io(window.location, {
                transports: ['websocket']
            })
            console.log("initializing socket", this.socket)

            this.socket.on('connect', (data) => {
                console.log("=== socket connected ====")
            })

            this.socket.on('disconnect', (data) => {
                console.log("=== socket disconnected ====")
            })

            this.socket.on('error', (data) => {
                console.log("socekt error", data)
            })

        } catch (error) {
            console.log("scoket is not inialized", error)
        }
    }

    emit(event, data = {}) {
        this.socket.emit(event, data)
    }
    
    on(event, cb) {
        this.socket.on(event, cb)
    }

    removeListener(listenerName) {
        this.socket.removeListener(listenerName)
    }

}

Don't specify the host/port for socket-io to connect to. It can figure it out on its own.

Per documentation, it tries to connect to window.location if no URL is specified as an argument.

So instead of

            this.socket = io(SOCKET_URL, {
                transports: ['websocket']
            })

Just do

            this.socket = io()

I am not sure it works with other arguments. You could try like this

            this.socket = io(undefined, {
                transports: ['websocket']
            })
Related