Home > other >  Unable to connect to socket.io server over local network
Unable to connect to socket.io server over local network

Time:03-18

I am trying to set up communication between my nodeJS server and a vueJS app via socket.io. I have been able to get the socket communication working on my main computer so far. When running my node server and my vue app in dev mode, I can open the vue app in the browser and I see the connection coming through my server.

However, when I open the vueJS app on my iPad (connected to the same wifi) the vue app loads and runs fine but my socket connection never goes through. I am also unable to connect to the socket server by opening the vueJS app on differnet PC (also connected to the same wifi as the PC serving the apps) so the iPad is not the issue here.

Could there be something with my local network that would be blocking the connection?

I have tried setting up the socket connection with plain socket.io client, vue-socketIO, and vue-socketIO-extended but each library had the same issue. Here is my code using vue-socketIO-extended:

main.js

import VueSocketIOExt from 'vue-socket.io-extended';
import { io } from 'socket.io-client';

const socket = io('http://localhost:3000');
Vue.use(VueSocketIOExt, socket);

App.js

  sockets: {
    connect() {
      // Fired when the socket connects.
      console.log('connect')
    },

    disconnect() {
      console.log('disconnect')
    }
  }

server.js

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
  cors: {
    origins: ['http://localhost:8080']
  }
});


app.get('/', (req, res) => {
  res.send('<h1>Hey Socket.io</h1>');
});


io.on('connection', (socket) => {

  console.log('a user connected');

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

  socket.on('my message', (msg) => {
    io.emit('my broadcast', `server: ${msg}`);
  });

});


http.listen(3000, () => {
  console.log('listening on *:3000');
});

CodePudding user response:

That's because the browser tries to connect to the WS server at http://localhost:3000, localhost resolves to IP 127.0.0.1 which is the loopback address of your device, on your iPad localhost is the iPad and there is nothing running on 127.0.0.1:3000 on the iPad.

You need to use the IP of the device that runs your server, Ex:
const socket = io('http://192.168.0.2:3000');

  • Related