Once you have installed the Socket.IO server library, you can now init the server. The complete list of options can be found here.
一旦安装了Socket.IO服务器库,就可以初始化服务器了。 选项的完整列表可以在这里找到。
1 | const options = { /* ... */ }; |
You can also pass the port as the first argument:
您还可以将端口作为第一个参数传递:
1 | const options = { /* ... */ }; |
This implicitly starts a Node.js HTTP server, which can be accessed through io.httpServer
.
这将隐式启动Node.js HTTP服务器,可以通过io.httpServer对其进行访问。
Attached to an existing HTTP server
1 | const server = require('http').createServer(); |
With HTTPS:
1 | const fs = require('fs'); |
With Express
1 | const app = require('express')(); |
More information here.
With Koa
1 | const app = require('koa')(); |
More information here.
Notable options(值得注意的配置)
The complete list of options can be found here. Here are those which you will most likely use:
选项的完整列表可以在这里找到。 以下是您最有可能使用的那些:
perMessageDeflate
option(perMessageDeflate选项)
Default value: true
The WebSocket server provided by the ws package supports the permessage-deflate extension, which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each WebSocket message.
As of Socket.IO v2, it is enabled by default, though it adds a significant overhead in terms of performance and memory consumption (and the ws maintainers suggest to only enable it if it is really needed).
So you can disable it with:
默认值:true
ws软件包提供的WebSocket服务器支持permessage-deflate扩展,该扩展使客户端和服务器能够协商压缩算法及其参数,然后有选择地将其应用于每个WebSocket消息的数据有效载荷。
从Socket.IO v2开始,默认情况下启用了该功能,尽管它在性能和内存消耗方面增加了可观的开销(并且ws维护人员建议仅在确实需要时才启用它)。
因此,您可以通过以下方式禁用它:
1 | const io = require('socket.io')({ |
Please note that it will be disabled by default in Socket.IO v3.
请注意,默认情况下它将在Socket.IO v3中禁用。
maxHttpBufferSize
option(maxHttpBufferSize选项)
Default value: 10e7
This defines how many bytes a message can be, before closing the socket. It defaults to 10e7
(100MB). You may increase or decrement this value depending on your needs.
默认值:10e7
这定义了在关闭套接字之前消息可以为多少字节。 默认为10e7(100MB)。 您可以根据需要增加或减少该值。
It matches the maxPayload option of the ws package.
它与ws软件包的maxPayload选项匹配。
Caught a mistake? Edit this page on GitHub