广播数据
将模拟数据发送到多个 WebSocket 客户端。
你可以通过在与这些客户端连接匹配的 WebSocket 链路上调用 .broadcast()
方法向多个 WebSocket 客户端发送数据:
¥You can send data to multiple WebSocket clients by calling the .broadcast()
method on the WebSocket link matching those client connections:
import { ws } from 'msw'
const chat = ws.link('wss://chat.example.com')
export const handlers = [
chat.addEventListener('connection', () => {
chat.broadcast('Hello, everyone!')
}),
]
与
client.send()
方法类似,你可以广播 各种数据类型。¥Similar to the
client.send()
method, you can broadcast various data types.
这将向所有被拦截的 WebSocket 客户端发送相同的数据。
¥This will send the same data to all intercepted WebSocket clients.
示例
¥Examples
排除客户端
¥Excluding clients
你可以使用 WebSocket 链接的 broadcastExcept()
方法,并向其提供要排除的 client
实例,将特定客户端从广播中排除:
¥You can exclude a specific client from the broadcast by using the broadcastExcept()
method of the WebSocket link and providing it with the client
instance to exclude:
import { ws } from 'msw'
const chat = ws.link('wss://chat.example.com')
export const handlers = [
chat.addEventListener('connection', (client) => {
client.addEventListener('message', (event) => {
// Whenever this client sends a message,
// broadcast it to all other clients.
chat.broadcastExcept(client, event.data)
})
}),
]
你还可以提供一个客户端列表作为 broadcastExcept()
方法的第一个参数,以便更好地控制哪些客户端被排除在广播之外:
¥You can also provide a list of clients as the first argument to the broadcastExcept()
method to have a finer control over which clients get excluded from the broadcast:
chat.addEventListener('connection', () => {
chat.broadcastExcept(
chat.clients.filter((client) => {
return client
}),
'Hello to some of you!',
)
})
WebSocket 链接的
clients
属性包含所有被拦截客户端的数组。¥The
clients
property of your WebSocket link contains an array of all intercepted clients.