@a1motion/express-ws 中文文档教程

发布于 5年前 浏览 23 项目主页 更新于 3年前

express-ws Dependency Status

WebSocket 端点Express 应用程序。 允许您像任何其他类型的路由一样定义 WebSocket 端点,并应用常规的 Express 中间件。 WebSocket 支持是在 ws 库的帮助下实现的。

Installation

npm install --save express-ws

Usage

可以在下面的 API 部分找到完整的文档。 本节仅显示一个简短示例。

将此行添加到您的 Express 应用程序中:

var expressWs = require('express-ws')(app);

重要提示:确保像上面那样设置 express-ws 模块之前 加载或定义你的路由器! 否则,express-ws 将没有机会设置对 Express 路由器的支持,并且你可能会遇到类似于 < code>router.ws 不是函数。

设置完 express-ws 后,您将能够(几乎)像添加其他路由一样添加 WebSocket 路由。 以下代码段在 /echo 设置了一个简单的回显服务器。 ws 参数是描述的 WebSocket 类的实例 这里

app.ws('/echo', function(ws, req) {
  ws.on('message', function(msg) {
    ws.send(msg);
  });
});

它也适用于路由器,这次在 /ws-stuff/echo

var router = express.Router();

router.ws('/echo', function(ws, req) {
  ws.on('message', function(msg) {
    ws.send(msg);
  });
});

app.use("/ws-stuff", router);

Full example

var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);

app.use(function (req, res, next) {
  console.log('middleware');
  req.testing = 'testing';
  return next();
});

app.get('/', function(req, res, next){
  console.log('get route', req.testing);
  res.end();
});

app.ws('/', function(ws, req) {
  ws.on('message', function(msg) {
    console.log(msg);
  });
  console.log('socket', req.testing);
});

app.listen(3000);

API

expressWs(app, server, options)

在指定的 app 上设置 express-ws。 这也将修改 Express 的全局 Router 原型 - 请参阅 leaveRouterUntouched 选项以获取有关禁用此功能的更多信息。

  • app: The Express application to set up express-ws on.
  • server: Optional. When using a custom http.Server, you should pass it in here, so that express-ws can use it to set up the WebSocket upgrade handlers. If you don't specify a server, you will only be able to use it with the server that is created automatically when you call app.listen.
  • options: Optional. An object containing further options.
  • leaveRouterUntouched: Set this to true to keep express-ws from modifying the Router prototype. You will have to manually applyTo every Router that you wish to make .ws available on, when this is enabled.
  • wsOptions: Options object passed to WebSocketServer constructor. Necessary for any ws specific features.

此函数将返回一个新的 express-ws API 对象,在文档的其余部分中将其称为 wsInstance

wsInstance.app

此属性包含设置了 express-wsapp

wsInstance.getWss()

返回底层 WebSocket 服务器/处理程序。 您可以使用 wsInstance.getWss().clients 获取此服务器的所有已连接 WebSocket 客户端的列表。

请注意,此列表将包括所有 客户端,而不仅仅是特定路由的客户端 - 这意味着将其用于广播等通常不是一个好主意。

wsInstance.applyTo(router)

在给定的 router(或其他类似 Router 的对象)上设置 express-ws。 您只在两种情况下需要它:

  1. You have enabled options.leaveRouterUntouched, or
  2. You are using a custom router that is not based on the express.Router prototype.

在大多数情况下,您根本不需要它。

Development

这个模块是用 ES6 编写的,并使用 ESM。

express-ws Dependency Status

WebSocket endpoints for Express applications. Lets you define WebSocket endpoints like any other type of route, and applies regular Express middleware. The WebSocket support is implemented with the help of the ws library.

Installation

npm install --save express-ws

Usage

Full documentation can be found in the API section below. This section only shows a brief example.

Add this line to your Express application:

var expressWs = require('express-ws')(app);

Important: Make sure to set up the express-ws module like above before loading or defining your routers! Otherwise, express-ws won't get a chance to set up support for Express routers, and you might run into an error along the lines of router.ws is not a function.

After setting up express-ws, you will be able to add WebSocket routes (almost) the same way you add other routes. The following snippet sets up a simple echo server at /echo. The ws parameter is an instance of the WebSocket class described here.

app.ws('/echo', function(ws, req) {
  ws.on('message', function(msg) {
    ws.send(msg);
  });
});

It works with routers, too, this time at /ws-stuff/echo:

var router = express.Router();

router.ws('/echo', function(ws, req) {
  ws.on('message', function(msg) {
    ws.send(msg);
  });
});

app.use("/ws-stuff", router);

Full example

var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);

app.use(function (req, res, next) {
  console.log('middleware');
  req.testing = 'testing';
  return next();
});

app.get('/', function(req, res, next){
  console.log('get route', req.testing);
  res.end();
});

app.ws('/', function(ws, req) {
  ws.on('message', function(msg) {
    console.log(msg);
  });
  console.log('socket', req.testing);
});

app.listen(3000);

API

expressWs(app, server, options)

Sets up express-ws on the specified app. This will modify the global Router prototype for Express as well - see the leaveRouterUntouched option for more information on disabling this.

  • app: The Express application to set up express-ws on.
  • server: Optional. When using a custom http.Server, you should pass it in here, so that express-ws can use it to set up the WebSocket upgrade handlers. If you don't specify a server, you will only be able to use it with the server that is created automatically when you call app.listen.
  • options: Optional. An object containing further options.
  • leaveRouterUntouched: Set this to true to keep express-ws from modifying the Router prototype. You will have to manually applyTo every Router that you wish to make .ws available on, when this is enabled.
  • wsOptions: Options object passed to WebSocketServer constructor. Necessary for any ws specific features.

This function will return a new express-ws API object, which will be referred to as wsInstance in the rest of the documentation.

wsInstance.app

This property contains the app that express-ws was set up on.

wsInstance.getWss()

Returns the underlying WebSocket server/handler. You can use wsInstance.getWss().clients to obtain a list of all the connected WebSocket clients for this server.

Note that this list will include all clients, not just those for a specific route - this means that it's often not a good idea to use this for broadcasts, for example.

wsInstance.applyTo(router)

Sets up express-ws on the given router (or other Router-like object). You will only need this in two scenarios:

  1. You have enabled options.leaveRouterUntouched, or
  2. You are using a custom router that is not based on the express.Router prototype.

In most cases, you won't need this at all.

Development

This module is written in ES6 and uses ESM.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文