dj43
dj43

Reputation: 73

how to use http server and socket connection together

I am using http server with socket connection response of http request goes when client responds to socket connection i am currently doing it by storing res in a global object which i think is not a correct method, what is the correct method to do it.

const app = require('express')()
bodyParser = require('body-parser')
app.use(bodyParser.json())
const net = require('net');
var client;
var res1,currentReq;

//----------------------------------------------------------------------------
// http requests listener
//----------------------------------------------------------------------------

app.listen(8001, () => console.log('Http server listening on port 8001'));

//----------------------------------------------------------------------------
// http requests handling
//----------------------------------------------------------------------------

app.post('/makeCall', (req, res) => {
        console.log('sd' + req.body)
        res1 = res;
        currentReq='makeCall';
        client.write("something");

});

//----------------------------------------------------------------------------
// Establishing tcp connection for incoming requests
//----------------------------------------------------------------------------

var server = net.createServer(function(connection) {
   console.log ('client has connected successfully!');
   client = connection;
   client.on('data',function(data){
   switch(currentReq) 
   {
       case 'makeCall' :
                    res1.end(data);
                    break;
   }

  });
});


//----------------------------------------------------------------------------
// listener for tcp connections
//----------------------------------------------------------------------------

server.listen(8000, function() {
   console.log('server for localhost is listening on port 8000');
});

Upvotes: 1

Views: 3267

Answers (1)

Codebling
Codebling

Reputation: 11382

Based on our discussion in comments, here is an example of how one might do this using socket.io.

Using a socket.io set-up, the browser will connect to the HTTP server to make HTTP GET AND POST requests, e.g. to /makeCall. The browser will also connect to the same HTTP server to open the socket. The browser will connect by HTTP initially, then send a special handshake which will convert the connection into a WebSocket.

I still am not sure to understand your use case so perhaps this solution is not appropriate, but here is the general setup of what it might look like.

const app = require('express')()
const bodyParser = require('body-parser')
const server = require('http').Server(app);
const io = require('socket.io')(server);
const cookieSession = require('cookie-session')

app.use(bodyParser.json())
app.use(cookieSession({
  keys: ['secret key', 'another one', 'a third one'],
  maxAge: 24 * 60 * 60 * 1000 // cookie max-age : 24 hours
}))


//----------------------------------------------------------------------------
// http requests listener
//----------------------------------------------------------------------------
server.listen(8001, () => console.log('Http server listening on port 8001'));
// WARNING: app.listen() will NOT work here! per socket.io docks

const idToSocketMap = new Map();

//----------------------------------------------------------------------------
// http requests handling
//----------------------------------------------------------------------------
app.post('/makeCall', (req, res) => {
  console.log('sd' + req.body)
  if (!req.session.id) {
    req.session.id = generateId();
  }

  //this may not be necessary, see below
  req.session.currentReq = 'makeCall';

  const socket = idToSocketMap.get(req.session.id)
  if (socket) { //if a socket connected for that id
    socket.emit("makeCall", "an argument/parameter", "something");
  }
});

//----------------------------------------------------------------------------
// Establishing websocket connection for incoming requests
//----------------------------------------------------------------------------
io.on('connection', (socket) => {
  //"socket" is now what would have been called "client" in old code

  //get the id from the session cookie of the http request
  const id = socket.request.session.id;
  //put the socket in the map
  idToSocketMap.set(id, socket);
  //remove the socket from the map on disconnect
  socket.on('disconnect', () => idToSocketMap.delete(id));

  console.log('client has connected successfully!');

  socket.on('makeCall', (firstParameter, something) => {
    // It's still not possible to send anything back to an HTTP connection
    // but we may do some things and reply here
    const someData = getSomeData();
    socket.emit('makeCallResponse', 'someData');
  });
});

Upvotes: 1

Related Questions