title: How to manage port for WebSocket, Socket and NodeJS application?
body: <p>I ended up using 3 different ports. <strong>777, 3000 and 4000</strong> and I still don't seem to have a desired result.</p>
  
  <p><strong>I get below error: socket.io.js:2 GET <a href="http://localhost:3000/socket.io/?EIO=3&amp;transport=polling&amp;t=Mfj-Hqo" rel="nofollow noreferrer">http://localhost:3000/socket.io/?EIO=3&amp;transport=polling&amp;t=Mfj-Hqo</a> 404 because ofcourse my socket.io is using port 4000 and not 3000.</strong></p>
  
  <p>I am using WebSockets in Nodejs (net library / package) to receive real-time stream data from TCP socket connection using port 777. </p>
  
  <p>I am using socket.io library to create publish / subscribe socket connection (port 4000) within the application for end users and</p>
  
  <p>finally, I am running nodejs application in port 3000</p>
  
  <p><strong>If I try to use port 3000 for socket.io, I get an error: port already in use.</strong></p>
  
  <h1>Updated</h1>
  
  <p><strong>How to use same port for both socket.io and nodejs application? that is use port 3000.</strong></p>
  
  <h1>Code</h1>
  
  <pre><code>var createError = require('http-errors');
  var express = require('express');
  var app = require('express')();
  var http = require('http').Server(express);
  var path = require('path');
  var cookieParser = require('cookie-parser');
  var logger = require('morgan');
  
  var indexRouter = require('./routes/index');
  var usersRouter = require('./routes/users');
  
  var io = require('socket.io')(http);
  io.listen(4000);
  var nsp = io.of('/channel1');
  var net = require('net');
  
  var server = net.createServer(function(socket) {
    socket.pipe(socket);
    socket.setEncoding('utf8');
    socket.on("data", function(d) {
      nsp.emit('live-data', d);
      console.log("DATA:", d);
    });
  });
  
  server.listen(777, '127.0.0.1');
  
  // view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'ejs');
  
  app.use(logger('dev'));
  app.use(express.json());
  app.use(express.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));
  
  app.use('/', indexRouter);
  app.use('/users', usersRouter);
  
  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
    next(createError(404));
  });
  
  // error handler
  app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
  
    // render the error page
    res.status(err.status || 500);
    res.render('error');
  });
  
  module.exports = app;
  </code></pre>