Answer the question
In order to leave comments, you need to log in
How to properly work with gorilla/websocket?
Hello, please help me deal with gorilla/websocket.
I don't understand how to work with him.
Here's what we have:
Create a hub:
type Hub struct {
clients map[*Client]bool
broadcast chan []byte
register chan *Client
unregister chan *Client
}
func NewHub() *Hub {
return &Hub{
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
clients: make(map[*Client]bool),
}
}
func Run(h *Hub) {
for {
select {
case client := <-h.register:
h.clients[client] = true
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
}
}
}
}
hub := ws.NewHub()
go ws.Run(hub)
....
r.HandleFunc("/socket", func(w http.ResponseWriter, r *http.Request) {
ws.ServeWs(hub, w, r)
})
const (
writeWait = 10 * time.Second
pongWait = 60 * time.Second
pingPeriod = (pongWait * 9) / 10
maxMessageSize = 512
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type Client struct {
hub *Hub
conn *websocket.Conn
send chan []byte
}
func ServeWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}
client.hub.register <- client
}
Answer the question
In order to leave comments, you need to log in
You can look at https://github.com/onrik/wshub , this is a wrapper over gorilla/websocket
In the ServeWs function, you register the client and immediately end the connection with it by exiting this function.
It needs to be different. Inside ServeWs, register a client and read his messages in a loop and send your own to him.
As a rough approximation, something like this:
func ServeWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
conn, err := wsupgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}
client.hub.register <- client
for {
var msg MsgType
err := conn.ReadJSON(&msg)
if err != nil {
client.hub.unregister <- client
return
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question