Skip to content
Nik Voss edited this page Jun 4, 2013 · 1 revision

Rooms are collections of connections. The main purpose for rooms is the ability to broadcast to them. If an event is emitted to a room all connections that joined the room will get the event. It is important to know that rooms only partly clean up after themselves. A connection will be forced to leave if emitting the event to the connection was not successful, but if no events are emitted the connection would stay in the room. To avoid inactive connections in rooms connections should always leave all rooms, when the connection is closed.

The first thing to do to work with rooms is to create a room:

var myroom = golem.NewRoom()

We could add an event to a router, too allow clients to join this room:

func join(conn *golem.Connection) {
	myroom.Join(conn)
	fmt.Println("Someone joined myroom.")
}
// ...
myrouter.On("join", join)

To test the capabilities of a room, we can add an event forwarding messages to the room:

type RoomMessage struct {
	Msg string `json:"msg"`
}
func msg(conn *golem.Connection, data *RoomMessage) {
	myroom.Emit("msg", &data)
	fmt.Println(data.Msg, "sent to members of myroom.")
}
// ...
myrouter.On("msg", msg)

And as previously mentioned we should make sure the connection leaves the room when it disconnects:

myrouter.OnClose(func(conn *golem.Connection) {
	myroom.Leave(conn)
})

To test the capabilities of the single room we created, we need a simple client testing if our room works. The client will join the room after successfully connecting and emitting a message to the room:

var conn = new golem.Connection("127.0.0.1:8080/ws", true);
conn.on("msg", function(data) {
    console.log(data.msg);
});
conn.on("open", function() {
    conn.emit("join");
    conn.emit("msg", { msg: "Hi room!"});
});

If we want to test the small application we could open multiple tabs and receive a "Hi room!"-Message in every previously opened browser tab.

The source of the server and client of this short single room illustration can be found in the example repository.

Clone this wiki locally