【发布时间】:2017-09-18 03:39:22
【问题描述】:
我正在尝试向特定房间发送消息,但它不起作用,它会向所有房间发送消息,同时我的消息从我的名字和第一个聊天室用户名收到两次。来自 1 个聊天室的消息会广播到所有聊天室。
我使用了这里的示例代码-https://github.com/kataras/iris/blob/master/_examples/websocket/secure/main.go。和 https://github.com/kataras/iris/blob/master/_examples/websocket/native-messages/main.go
下面是我正在使用的代码,这给了我错误:
var myChatRoom = strconv.Itoa(room.ID)
ws := websocket.New(websocket.Config{})
ws.OnConnection(func(c websocket.Connection) {
c.Join(myChatRoom)
c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Joined Chat!"))
c.OnMessage(func(data []byte) {
message := string(data)
if message == "leave" {
c.Leave(myChatRoom)
c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Left Chat!"))
return
}
c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + ": " + message))
})
c.OnDisconnect(func() {
fmt.Printf("Connection with ID: %s has been disconnected!\n", c.ID())
})
})
HTML 代码:
<div id="messages" style="border-width: 1px; border-style: solid; height: 200px;overflow:auto"></div>
<input type="text" id="messageTxt" />
<button type="button" id="sendBtn">Send</button>
Javascript 代码:
<script>
var messageTxt;
var messages;
var HOST = 'localhost'
jQuery(function() {
messageTxt = jQuery("#messageTxt");
messages = jQuery("#messages");
w = new WebSocket("ws://" + HOST + "/my_endpoint");
w.onopen = function() {
console.log("Websocket connection enstablished");
};
w.onclose = function() {
appendMessage(jQuery("<div><center><h3>Disconnected</h3></center></div>"));
};
w.onmessage = function(message) {
console.log("Message Appended: " + message)
appendMessage(jQuery("<div>" + message.data + "</div>"));
};
jQuery("#sendBtn").click(function() {
w.send(messageTxt.val().toString());
messageTxt.val("");
});
})
function appendMessage(messageDiv) {
messageDiv.appendTo(jQuery("#messages"));
}
</script>
错误:
它将消息发送到所有 ROOM 而不是特定的 Room。
先创建房间的用户会自动加入所有房间
在其他 ROOM 中发送消息的人看到他们的消息在他们的 ROOM 中被创建第一个聊天室的“FirstUser”重复/克隆。 (不管他是不是群成员)
预期:
人们只能向他们加入的房间发送/接收消息。
第一个用户应该不能自动加入 CHATRoom。
人们不应看到他们的消息再次以“FirstUser”名称重复。
【问题讨论】:
-
请写下你在运行你的 go 代码时遇到了什么错误。没有它就很难说发生了什么。
-
@Nebril - 错误消息已更新。
标签: javascript go websocket