go - 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
解决方案
推荐阅读
- python - 如何使用 Python 在 Spark 流中加入三个 DStream
- django - 如何更改重定向 URI?
- python - 使用 Python 从 Salesforce URL 下载图像
- php - 无法使用 cakePHP 3.7 将数据保存在多个表中
- javascript - ng-view 不加载页面
- android - 无法膨胀重复片段(com.google.android.gms.location.places.ui.PlaceAutocompleteFragment)
- excel - VBA中的图形计数器
- c++ - 创建 std::tuple 时从 const char* 或 char* 推导出 std::string
- java - 从应用程序上下文启动活动时的风险?
- nuget - Nuget 崩溃的视觉工作室 2019