in

Node: How to establish a WS connection between two PCs of different networks?


My friend and I are trying to connect our PC’s using sockets.
So my friend runs a simple WS-server like this:

const WebSocket = require('ws')

function onConnect(wsClient) {

  wsClient.on('message', (message) => {
    const buff = Buffer.from(message)
    console.log('new message', buff.toString())
  })

  wsClient.on('close', function() {
    console.log('connection closed');
  })
}

wsServer.on('connection', onConnect);

Its purpose is to show a message in terminal once one is received.

I run a simple WS cliend like this one (I use my friend’s public IP):

const WebSocket = require('ws')

wsServer = new WebSocket('ws://${IP}:9000')
wsServer.on('open', () => {
    wsServer.send(JSON.stringify('wsServer'))
})

When I run both a client and a server on my local machine everything works fine.
When I try to reach my friend’s PC I get en error like this:

Error: connect ETIMEDOUT ${IP}:9000

So I guess the problem is: when I hit the public IP the router does not know where to forward a request (since there are dozens of people who use it).

I have to general questions:

  1. Why there is no such error when I use some online chat? Its server can be a part of some local network as well.

  2. Is there a way to establish a safe P2P connection using sockets? If yes, how?

Thank you!



Source: https://stackoverflow.com/questions/70554273/node-how-to-establish-a-ws-connection-between-two-pcs-of-different-networks

Smile creator 4 – HEX EDITOR,Discord Nuker,Plugin Adder,Cheat Engine

A sample app showing how to implement biometric authentication in flutter