发送数据

将模拟数据发送到单个 WebSocket 客户端。

你可以通过在 connection 事件监听器中的任何位置调用 client.send() 来将数据发送到被拦截的 WebSocket 客户端:

¥You can send data to the intercepted WebSocket client by calling client.send() anywhere in the connection event listener:

api.addEventListener('connection', ({ client }) => {
  client.send('hello from server!')
})

你可以向客户端发送文本、BlobArrayBuffer

¥You can send text, Blob, and ArrayBuffer to the client.

这会将给定的数据发送到特定的 client,它将接收并处理该数据,就像从服务器接收一样。有关向多个客户端发送数据,请参阅 广播数据

¥This will send the given data to the particular client, and it will receive and handle it as if it was received from the server. For sending data to multiple clients, see broadcasting data.

示例

¥Examples

发送文本

¥Sending text

api.addEventListener('connection', ({ client }) => {
  client.send('hello world')
})

发送 Blob

¥Sending Blob

api.addEventListener('connection', ({ client }) => {
  client.send(new Blob(['hello world'], { type: 'text/plain' }))
})

发送 ArrayBuffer

¥Sending ArrayBuffer

api.addEventListener('connection', ({ client }) => {
  client.send(new TextEncoder().encode('hello world'))
})