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

标签 node.js express socket.io

我希望在具有 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/

相关文章:

node.js - 如何使用 ReSTLer 下载网站并将其写入文件?

node.js - Nodejitsu 说我的应用程序是 "not a Node app"- 是否有特殊的方法来编写用于 Nodejitsu 部署的 Node 应用程序?

node.js - 如何使用 Node.js 抓取异步加载数据的网站?

css - 在我的 Node Express 服务器上路由 css 时出现问题

javascript - socket.io 未发送到客户端

node.js - 在NodeJS端使用SocketIo读取数据?

javascript - 有哪些选项可用于定义具有 node.js 依赖项的 Python 包?

express - 如何为 webpack 模板添加后端?

javascript - 以下代码中何时调用/执行/调用 JavaScript 函数表达式?

python -/socket.io/* 404 未找到 flask