Created
December 5, 2019 21:14
-
-
Save danielsmykowski1/8a07b1353b0261d6b7cd7e75c8919d63 to your computer and use it in GitHub Desktop.
A Golang file that uses websocket in golang throught gorilla/websocket.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"log" | |
"net/http" | |
"time" | |
"github.com/gorilla/websocket" | |
) | |
const ( | |
writeWait = 10 * time.Second | |
pongWait = 60 * time.Second | |
pingPeriod = (pongWait * 9) / 10 | |
maxMessageSize = 512 | |
) | |
var ( | |
newline = []byte{'\n'} | |
space = []byte{' '} | |
) | |
var upgrader = websocket.Upgrader{ | |
ReadBufferSize: 1024, | |
WriteBufferSize: 1024, | |
} | |
type Client struct { | |
hub *Hub | |
conn *websocket.Conn | |
send chan []byte | |
} | |
func (c *Client) readMessages() { | |
defer func() { | |
c.hub.unregister <- c | |
c.conn.Close() | |
}() | |
c.conn.SetReadLimit(maxMessageSize) | |
c.conn.SetReadDeadline(time.Now().Add(pongWait)) | |
c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) | |
for { | |
_, message, err := c.conn.ReadMessage() | |
if err != nil { | |
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { | |
log.Printf("error: %v", err) | |
} | |
break | |
} | |
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1)) | |
c.hub.broadcast <- message | |
} | |
} | |
func (c *Client) writeMessages() { | |
ticker := time.NewTicker(pingPeriod) | |
defer func() { | |
ticker.Stop() | |
c.conn.Close() | |
}() | |
for { | |
select { | |
case message, ok := <-c.send: | |
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) | |
if !ok { | |
// The hub closed the channel. | |
c.conn.WriteMessage(websocket.CloseMessage, []byte{}) | |
return | |
} | |
w, err := c.conn.NextWriter(websocket.TextMessage) | |
if err != nil { | |
return | |
} | |
w.Write(message) | |
n := len(c.send) | |
for i := 0; i < n; i++ { | |
w.Write(newline) | |
w.Write(<-c.send) | |
} | |
if err := w.Close(); err != nil { | |
return | |
} | |
case <-ticker.C: | |
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) | |
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil { | |
return | |
} | |
} | |
} | |
} | |
func serveWebsocket(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 | |
go client.writeMessages() | |
go client.readMessages() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment