Kamal Palei
Kamal Palei

Reputation: 2022

Javascript: Can I open websocket server connection at random port

I want to create webserver socket connection at random port. And I want to return server port to calling application or just print it in terminal.

The typical code to create a server connection is as below.

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 0 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

So I am trying to create server at port 0. I assume it will create server at random port. How do I get that random port?

I want to know the port number, as soon as server socket is created.

Upvotes: 1

Views: 1609

Answers (2)

Kamal Palei
Kamal Palei

Reputation: 2022

Now I am able to create the websocket server at random port and able to get the port number as well. Not sure if it is the right way, but it works.

const http = require('http');
const WebSocket = require('ws');
const url = require('url');

const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });

wss.on('connection', function connection(ws) {
  console.log(wss);
});

server.on('upgrade', function upgrade(request, socket, head) {
  const pathname = url.parse(request.url).pathname;

    wss.handleUpgrade(request, socket, head, function done(ws) {
      wss.emit('connection', ws, request);
    });
});

server.listen(0, '127.0.0.1', function incoming() {console.log (server.address().port);});

Upvotes: 2

parveen
parveen

Reputation: 577

Websocket works with http/s on port 80 or 443. The server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. Browsers generally require a secure connection for WebSockets, although they may offer an exception for local devices.

Upvotes: 0

Related Questions