javascript - 如何同时使用http服务器和socket连接

标签 javascript node.js express

我正在使用http服务器,当客户端响应套接字连接时,http请求的套接字连接响应就会发生,我目前通过将res存储在全局对象中来实现,我认为这不是正确的方法,正确的方法是什么?

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');
});

最佳答案

根据我们在评论中的讨论,以下是如何使用 socket.io 执行此操作的示例.

使用 socket.io 设置,浏览器将连接到 HTTP 服务器以发出 HTTP GETPOST 请求,例如到 /makeCall。浏览器还将连接到相同 HTTP 服务器以打开套接字。浏览器最初将通过 HTTP 连接,然后发送特殊的握手,将连接转换为 WebSocket。

我仍然不确定您的用例,所以也许这个解决方案不合适,但这里是它可能看起来像的一般设置。

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');
  });
});

关于javascript - 如何同时使用http服务器和socket连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60540043/

相关文章:

Node.js 使用异步/等待读取文件

javascript - 在 node.js 中传递对 express-resources 的引用?

javascript - 如何仅引用文件中的一个变量而不是node.js 中的所有导出?

Node.js 请求为什么在 try catch 中捕获 400 响应

javascript - navigator.notification.* 失败 "navigator.notification [undefined] is not an object"

javascript - Eclipse Javascript——如何订购多个文件?

javascript - amCharts 动态数据传递

javascript - 如何在 selenium-webdriver nodejs land 中更改 selenium 用户代理?

node.js - 我在 Express App 上看不到环境变量

javascript - NodeJS 与 MongoDB - 实例化 "db"变量的最佳实践