Ad

How To Manage Port For WebSocket, Socket And NodeJS Application?

- 1 answer

I ended up using 3 different ports. 777, 3000 and 4000 and I still don't seem to have a desired result.

I get below error: socket.io.js:2 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=Mfj-Hqo 404 because ofcourse my socket.io is using port 4000 and not 3000.

I am using WebSockets in Nodejs (net library / package) to receive real-time stream data from TCP socket connection using port 777.

I am using socket.io library to create publish / subscribe socket connection (port 4000) within the application for end users and

finally, I am running nodejs application in port 3000

If I try to use port 3000 for socket.io, I get an error: port already in use.

Updated

How to use same port for both socket.io and nodejs application? that is use port 3000.

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;
Ad

Answer

From the official readme of socket.io

const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ }); 
server.listen(3000);

That's will let you use the same port for express and socket.io.

Ad
source: stackoverflow.com
Ad