javascriptnode.jswebsocketsocket.iolocalhost

Connect to local node.js server that is hosted by my pc and connect through phone that is usb-tethered


I'm hosting a localserver node.js server that uses websockets, and a frontend app through liveserver extension That is happening on my laptop, it gets access to internet through my phone using usb-tethering, I was wondering is it possible, and if yes how, to connect to this local server that my laptop is hosting I tried to open up it on the phone by entering my laptop's ip adress that I got from ipconfig in shell and I opened two folders

It was possible to open frontend app, but it didn't connect to server, it if firewall problem? Or something else?

Client code:

const socket = io('ws://localhost:3500')

function sendMessage(e) {
    e.preventDefault()
    const input = document.querySelector('input')
    if (input.value) {
        socket.emit('message', input.value)
        input.value = ""
    }
    input.focus()
}

document.querySelector('form').addEventListener('submit',sendMessage)

// Listen for messages
socket.on('message', (data) => {
    const li = document.createElement('li')
    li.textContent = data
    document.querySelector('ul').appendChild(li)
})

Server code:

import { createServer } from "http"
import { Server } from "socket.io"

const httpServer = createServer()

const io = new Server(httpServer, {
    cors: {
        origin: "*"
    }
})


io.on('connection', socket => {
    console.log(`User ${socket.id} connected`)

    socket.on('message', data => {
        console.log(data)
        io.emit('message', `${socket.id.substring(0,5)}: ${data}`)

    })
})


httpServer.listen(3500, () => console.log('listening'))



I have put a firewall inbound rule for port 3500 but nothing has changed


Solution

  • In your client code, change first line

    const socket = io('ws://localhost:3500')
    

    to

    const socket = io('ws://<YOUR_PC_IPADRESS>:3500')
    

    That's because your phone is trying to connect to localhost which is loopback address. So it tries to connect to websocket server running on itself.