客户端到服务器转发

管理客户端事件转发。

默认情况下,你从 WebSocket 客户端发送的任何事件都不会转发到原始服务器,因为原始服务器连接尚未建立。你可以通过在事件处理程序中调用 server.connect() 来选择 建立服务器连接。完成后,所有客户端事件都将被转发到原始服务器。

¥By default, none of the events you send from your WebSocket client are forwarded to the original server because the original server connection is not established. You can choose to establish the server connection by calling server.connect() in your event handler. Once you do, all the client events will be forwaded to that original server.

你可以通过多种方式管理该事件转发:

¥You can manage that event forwarding in multiple ways:

  • 代理事件(即不执行任何操作);

    ¥Proxy the events (i.e. do nothing);

  • 将修改后的客户端事件发送到服务器;

    ¥Send modified client events to the server;

  • 完全阻止客户端事件到达服务器。

    ¥Prevent client events from reaching the server entirely.

阻止客户端事件

¥Preventing client events

你可以通过在 WebSocket 客户端分派的任何事件的事件监听器中调用 event.preventDefault() 来阻止该事件被转发到原始服务器。

¥You can prevent any event dispatched by your WebSocket client from being forwarded to the original server by calling event.preventDefault() in the event listener for that event.

api.addEventListener('connection', ({ client, server }) => {
  server.connect()
 
  client.addEventListener('message', (event) => {
    event.preventDefault()
  })
})

例如,这里我们阻止任何来自客户端的 message 事件到达原始服务器。你仍然可以在监听器中观察已调度的客户端消息,但它们将不再转发到服务器。

¥For example, here we are preventing any message event from the client from ever reaching the original server. You can still able to observe the dispatched client messages in the listener but they will not be forwarded to the server anymore.

与常规事件一样,你可以有条件地阻止默认事件:

¥Just like with regular events, you can prevent the default conditionally:

api.addEventListener('connection', ({ client, server }) => {
  server.connect()
 
  client.addEventListener('message', (event) => {
    // Skip the forwarding only for particular client messages.
    if (event.data === 'hello world') {
      event.preventDefault()
    }
  })
})

修改客户端事件

¥Modifying client events

修改客户端事件分为两步:

¥Modifying a client event comes down to two steps:

  1. 阻止该事件(即 event.preventDefault())的转发;

    ¥Preventing the forwarding for that event (i.e. event.preventDefault());

  2. 改为将修改后的(模拟的)事件发送到服务器(即 server.send())。

    ¥Sending a modified (mocked) event to the server instead (i.e. server.send()).

让我们扩展上一个示例,并在阻止客户端消息事件后发送一个修改后的事件:

¥Let’s expand on the previous example and send a modified client message event after it’s been prevented:

api.addEventListener('connection', ({ client, server }) => {
  server.connect()
 
  client.addEventListener('message', (event) => {
    // Skip the forwarding only for particular client messages.
    if (event.data === 'hello world') {
      event.preventDefault()
      server.send('hello cosmos')
    }
  })
})

相关材料

¥Related materials

以类似的方式,你可以管理服务器事件的转发。

¥In a similar manner, you can manage the forwarding of the server events.

Server-to-client forwarding

Manage the server event forwarding.