首页 > 解决方案 > Gorilla/websocket 中的回调

问题描述

我正在尝试在 Go 中构建多人游戏后端。我以前在 Node JS (socket.io) 中工作过,我记得能够在我的前端为不同的消息注册回调,如下所示:

  componentDidMount() {
this.socket.on('join_room', (clients) => {
  //do smt
});
this.socket.on('user_image', (data) => {
  // do smt
});

}

在 gorilla/websockets 中,我只能从后端接收一般消息。如何区分消息类型?有没有办法注册某种类似于socket.io的回调?

            let conn = new WebSocket("ws://" + document.location.host + "/ws/" + roomId);
            conn.onclose = function (evt) {
                let item = document.createElement("div");
                item.innerHTML = "<b>Connection closed.</b>";
                appendLog(item);
            };
            conn.onmessage = function (evt) {
                let messages = evt.data.split('\n');
                for (let i = 0; i < messages.length; i++) {
                    let item = document.createElement("div");
                    item.innerText = messages[i];
                    appendLog(item);
                }

我使用这个 repo 作为我的后端代码的例子:https ://github.com/AnupKumarPanwar/Golang-realtime-chat

标签: gowebsocketgorilla

解决方案


推荐阅读