gpt4 book ai didi

node.js - 现有node.js项目中的socket.io

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:45 26 4
gpt4 key购买 nike

我希望在具有 Node.js 后端的应用程序中实现实时更新。我想为此使用 socket.io 并且我了解需要实现的库。但是,我已经有一个正在运行的 Node.js 服务器:

app.listen(process.env.PORT, () => {

console.log("Server is up and running")

})

问题相当简单:是否可以使用具有相同端口的同一服务器来监听 socket.io 连接,或者我应该完全在不同的服务器上运行它,或者只是为此打开另一个端口?因为我在例子中经常看到的是它监听http。见下文。

我平时看到的(本例来自this post)

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

http.listen(3000, function () {
console.log('listening on *:3000');
});

现在,如果我使用相同的服务器和端口,我怎样才能监听传入的 socket.io 请求或发送给其客户端?我可以继续使用 app.listen 监听吗?它也会连接到 socket.io 吗?

最佳答案

简而言之,是的,套接字连接作为同一地址和端口上的 http 请求启动。

The WebSocket protocol was designed to work well with the existing Web infrastructure. As part of this design principle, the protocol specification defines that the WebSocket connection starts its life as an HTTP connection, guaranteeing full backwards compatibility with the pre-WebSocket world. The protocol switch from HTTP to WebSocket is referred to as a the WebSocket handshake.

At this point the HTTP connection breaks down and is replaced by the WebSocket connection over the same underlying TCP/IP connection. The WebSocket connection uses the same ports as HTTP (80) and HTTPS (443), by default.

https://websocket.org/aboutwebsocket.html

关于node.js - 现有node.js项目中的socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55554225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com