You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让两个WebSocket onmessage事件处理器同时运行处理对应数据

问题原因

WebSocket.onmessage是单值属性,同一时间只能绑定一个处理函数。你现在每次调用sendMessage1/sendMessage2都会给onmessage赋新的函数,后执行的绑定会直接覆盖之前的逻辑,最终所有服务端返回的消息只会走最后一次绑定的处理流程,自然无法分别填充两个列表。

修复方案

不要在发送消息的函数里重复绑定onmessage,只在WebSocket初始化时绑定唯一的全局消息处理函数,再根据服务端返回数据的区分标识,把消息路由到对应的列表渲染即可。

修正后代码

JavaScript部分

// WebSocket初始化逻辑(仅执行一次)
const ws = new WebSocket('替换为你的WebSocket服务地址')
// 维护消息类型和对应列表容器的映射关系,key需要和服务端返回的标识字段匹配
const listRouter = {
  channel1: 'messages1',
  channel2: 'messages2'
}

// 全局唯一的消息处理函数,仅绑定一次
ws.onmessage = function(event) {
  const parsed = JSON.parse(event.data)
  // 此处parsed.type为服务端返回的消息类型标识,根据实际接口字段名调整
  const targetListId = listRouter[parsed.type]
  if (!targetListId) return // 无匹配列表的消息直接忽略
  const listContainer = document.getElementById(targetListId)
  const messageItem = document.createElement('li')
  messageItem.appendChild(document.createTextNode(JSON.stringify(parsed.data)))
  listContainer.appendChild(messageItem)
}

function sendMessage1(event) {
  event.preventDefault()
  const input = document.getElementById("messageText1")
  // 发送消息时带上对应类型标识,具体格式按你的服务端要求调整
  ws.send(JSON.stringify({
    type: 'channel1',
    content: input.value
  }))
  input.value = ''
}

function sendMessage2(event) {
  event.preventDefault()
  const input = document.getElementById("messageText2")
  ws.send(JSON.stringify({
    type: 'channel2',
    content: input.value
  }))
  input.value = ''
}

HTML部分

原有HTML结构无需修改,可直接复用:

<div class="flex-container">
        <div class="flex-child">
            <form action="" onsubmit="sendMessage1(event)">
                <input type="text" id="messageText1" autocomplete="off" />
                <button>Send</button>
            </form>
            <ul id='messages1'>
                <li>Enter Channel Subscription Above</li>
            </ul>
        </div>
        <div class="flex-child">
            <form action="" onsubmit="sendMessage2(event)">
                <input type="text" id="messageText2" autocomplete="off" />
                <button>Send</button>
            </form>
            <ul id='messages2'>
                <li>Enter Channel Subscription Above</li>
            </ul>
        </div>
    </div>

适配说明

  • 如果你的WebSocket服务本身返回的数据就自带通道区分字段(比如订阅多频道推送时返回的频道名、stream字段等),不需要修改前端发送消息的格式,直接把返回数据里的对应字段作为路由判断依据,调整listRouter的映射关系即可。
  • 禁止在业务逻辑中重复给ws.onmessage赋值,避免处理逻辑被覆盖。

内容的提问来源于stack exchange,提问作者maumau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 22:42:29