I am trying to send Message to Particular Room, but it doesn't work and It sends message to all room along with my message being received twice from my name and with first chat room user name. Message from 1 Room is broadcasted to all Chat Room.

I have used Example Code from here- https://github.com/kataras/iris/blob/master/_examples/websocket/secure/main.go. and https://github.com/kataras/iris/blob/master/_examples/websocket/native-messages/main.go

Below is the Code, I am using, that is giving me the error :

        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!
", c.ID())
            })
        })

HTML Code:

<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 Code:

<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>

Error:

  1. It sends message to all ROOM and not specific Room.

  2. User who created room first automatically joins all the ROOM

  3. People sending message in other ROOM see their message being Repeated/cloned in their ROOM by "FirstUser" who created first room in chat. (Irrespective of whether he is member of the chat group or not)

Expecting:

  1. People can send/receive message to only those room where they have joined.

  2. First User should not be able to join CHATRoom automatically.

  3. People should not see their message being repeated again with "FirstUser" name.