├── main.go ├── README.md ├── LICENSE ├── client.go ├── hub.go └── room.go /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "github.com/gorilla/mux" 6 | "log" 7 | "net/http" 8 | ) 9 | 10 | var addr = flag.String("addr", "localhost:8080", "http service address") 11 | 12 | func main() { 13 | flag.Parse() 14 | log.SetFlags(0) 15 | hub := NewHub() 16 | router := mux.NewRouter() 17 | router.HandleFunc("/ws/{room}", hub.HandleWS).Methods("GET") 18 | 19 | http.Handle("/", router) 20 | 21 | log.Printf("http_err: %v", http.ListenAndServe(*addr, nil)) 22 | } 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Websocket rooms 2 | =============== 3 | 4 | A rewrite of an old websocket server with rooms. 5 | **Update**:This code is old and probably has race conditions. 6 | 7 | Testing it out 8 | ============== 9 | ``` 10 | # install 11 | go get -v github.com/godwhoa/wsrooms 12 | go get -v github.com/lafikl/telsocket 13 | 14 | # run server 15 | go run *.go 16 | 17 | # connect the client 18 | telsocket -url ws://localhost:8080/ws/test 19 | ``` 20 | 21 | TODO: 22 | ===== 23 | 24 | + ~~Clients talking to other clients~~ 25 | + ~~Fix the crash~~ 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 Joseph Daniel 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/gorilla/websocket" 5 | "log" 6 | ) 7 | 8 | /* To figure out if they wanna broadcast to all or broadcast to all except them */ 9 | type Message struct { 10 | mtype string 11 | msg []byte 12 | } 13 | 14 | /* Reads and writes messages from client */ 15 | type Client struct { 16 | conn *websocket.Conn 17 | out chan Message 18 | } 19 | 20 | /* Reads and pumps to out channel */ 21 | func (c *Client) ReadLoop() { 22 | defer close(c.out) 23 | for { 24 | _, message, err := c.conn.ReadMessage() 25 | if err != nil { 26 | // log.Println("read:", err) 27 | break 28 | } 29 | msg := Message{"ex", message} 30 | c.out <- msg 31 | } 32 | } 33 | 34 | /* Writes a message to the client */ 35 | func (c *Client) WriteMessage(msg []byte) { 36 | err := c.conn.WriteMessage(websocket.TextMessage, msg) 37 | if err != nil { 38 | log.Println("write:", err) 39 | } 40 | } 41 | 42 | /* Constructor */ 43 | func NewClient(conn *websocket.Conn) *Client { 44 | client := new(Client) 45 | client.conn = conn 46 | client.out = make(chan Message) 47 | return client 48 | } 49 | -------------------------------------------------------------------------------- /hub.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/gorilla/mux" 5 | "github.com/gorilla/websocket" 6 | "log" 7 | "net/http" 8 | ) 9 | 10 | /* Controls a bunch of rooms */ 11 | type Hub struct { 12 | hub map[string]*Room 13 | upgrader websocket.Upgrader 14 | } 15 | 16 | /* If room doesn't exist creates it then returns it */ 17 | func (h *Hub) GetRoom(name string) *Room { 18 | if _, ok := h.hub[name]; !ok { 19 | h.hub[name] = NewRoom(name) 20 | } 21 | return h.hub[name] 22 | } 23 | 24 | /* Get ws conn. and hands it over to correct room */ 25 | func (h *Hub) HandleWS(w http.ResponseWriter, r *http.Request) { 26 | params := mux.Vars(r) 27 | room_name := params["room"] 28 | 29 | c, err := h.upgrader.Upgrade(w, r, nil) 30 | if err != nil { 31 | log.Println("upgrade:", err) 32 | return 33 | } 34 | defer c.Close() 35 | room := h.GetRoom(room_name) 36 | id := room.Join(c) 37 | 38 | /* Reads from the client's out bound channel and broadcasts it */ 39 | go room.HandleMsg(id) 40 | 41 | /* Reads from client and if this loop breaks then client disconnected. */ 42 | room.clients[id].ReadLoop() 43 | room.Leave(id) 44 | } 45 | 46 | /* Constructor */ 47 | func NewHub() *Hub { 48 | hub := new(Hub) 49 | hub.hub = make(map[string]*Room) 50 | hub.upgrader = websocket.Upgrader{ 51 | ReadBufferSize: 1024, 52 | WriteBufferSize: 1024, 53 | CheckOrigin: func(r *http.Request) bool { 54 | return true 55 | }, 56 | } 57 | return hub 58 | } 59 | -------------------------------------------------------------------------------- /room.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/gorilla/websocket" 7 | ) 8 | 9 | /* Has a name, clients, count which holds the actual coutn and index which acts as the unique id */ 10 | type Room struct { 11 | name string 12 | clients map[int]*Client 13 | count int 14 | index int 15 | } 16 | 17 | /* Add a conn to clients map so that it can be managed */ 18 | func (r *Room) Join(conn *websocket.Conn) int { 19 | r.index++ 20 | r.clients[r.index] = NewClient(conn) 21 | log.Printf("New Client joined %s", r.name) 22 | r.count++ 23 | return r.index 24 | } 25 | 26 | /* Removes client from room */ 27 | func (r *Room) Leave(id int) { 28 | r.count-- 29 | delete(r.clients, id) 30 | } 31 | 32 | /* Send to specific client */ 33 | func (r *Room) SendTo(id int, msg []byte) { 34 | r.clients[id].WriteMessage(msg) 35 | } 36 | 37 | /* Broadcast to every client */ 38 | func (r *Room) BroadcastAll(msg []byte) { 39 | for _, client := range r.clients { 40 | client.WriteMessage(msg) 41 | } 42 | } 43 | 44 | /* Broadcast to all except */ 45 | func (r *Room) BroadcastEx(senderid int, msg []byte) { 46 | for id, client := range r.clients { 47 | if id != senderid { 48 | client.WriteMessage(msg) 49 | } 50 | } 51 | } 52 | 53 | /* Handle messages */ 54 | func (r *Room) HandleMsg(id int) { 55 | for { 56 | if r.clients[id] == nil { 57 | break 58 | } 59 | out := <-r.clients[id].out 60 | if out.mtype == "ex" { 61 | r.BroadcastEx(id, out.msg) 62 | } else { 63 | r.BroadcastAll(out.msg) 64 | } 65 | } 66 | } 67 | 68 | /* Constructor */ 69 | func NewRoom(name string) *Room { 70 | room := new(Room) 71 | room.name = name 72 | room.clients = make(map[int]*Client) 73 | room.count = 0 74 | room.index = 0 75 | return room 76 | } 77 | --------------------------------------------------------------------------------