安装
首先,确保你已经安装了 Fastify
和 WebSocket
相关的依赖包。如果尚未安装,可以使用以下命令安装:
# 安装fastify
npm i fastify
# 安装websocket
npm i @fastify/websocket
引入和注册 WebSocket 插件
在你的 JavaScript 文件中,首先创建 Fastify
服务实例,并引入 WebSocket
插件。然后,使用 fastify.register
方法注册 WebSocket
插件并进行配置,如下所示:
// 创建 Fastify 服务实例
const fastify = require("fastify")();
// 引入 WebSocket 插件
const websocket = require("@fastify/websocket");
// 注册 WebSocket 插件
fastify.register(websocket, {
cors: true,
options: {
maxPayload: 1048576
}
});
在上述代码中,cors
参数设置为 true
,表示允许跨域请求。options
参数用于配置其他选项,其中 maxPayload
设置为 1048576
字节(1MB),表示允许传输的最大数据量为 1MB
。
cors
是允许跨域的开关,参数为true
和false
,如果你没有跨域可以不用写这个参数
options中还有一些其他的参数配置
例如:
验证连接是否合法
info
是该websocket的详细信息,
next
是一个回调函数,接受两个参数,true
和false
,传true
的话则会执行后面注册的监听函数。
verifyClient: function (info, next) {
if (info.req.headers['x-fastify-header'] !== 'fastify is awesome !') {
return next(false) // the connection is not allowed
}
next(true) // the connection is allowed
}
注册路由和添加监听函数
接下来,你可以注册 WebSocket 的连接路由,并添加相应的监听函数。以下是一个示例:
const wsFn = async (connection, request) => {
// 获取query/body参数通过request对象获取
const { parm1 } = request.query
connection.socket.on('open', message => {
// 开始连接
console.log(`Received message: ${message}`)
const response = { data: 'hello, client' }
connection.socket.send(JSON.stringify(response))
})
connection.socket.on('message', async (message) => {
// 监听websocket的message事件来获取实时的通信数据,当然也可以去掉async/await
await connection.socket.send(JSON.stringify({"data": "实时发送的数据"}))
})
connection.socket.on('close', () => {
// 监听连接关闭事件
const response = { code: 403, data: 'Client disconnected',message: 'Client disconnected' }
connection.socket.send(JSON.stringify(response))
});
}
// 注册websocket的连接路由
fastify.register(async function(fastify) {
fastify.get('/ws/ws1', {
websocket: true
}, wsFn)
// wsFn改路由会执行的函数
})
在上述代码中,wsFn 是用于处理 WebSocket 连接的监听函数。当连接建立时,它会发送欢迎消息给客户端。接着,它监听 WebSocket 的 message 事件,以获取实时发送的数据。最后,它还监听连接关闭事件,并发送相应的响应消息。
启动 Fastify 的 HTTP 服务
最后,使用 fastify.listen 方法启动 Fastify 的 HTTP 服务,并指定要监听的端口和主机地址。例如:
// 启动服务器
const start = () => {
fastify.listen({ port: 3002, host: '0.0.0.0' }, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
console.info(`server listening on ${address}`)
});
};
start();
在上述代码中,start
函数使用 fastify.listen
方法来启动 Fastify 的 HTTP 服务。指定的 port
参数为 3002,host
参数为 '0.0.0.0'
,表示允许公网访问。当服务器成功启动后,会在控制台打印服务器的地址信息。