-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Dan
committed
Nov 7, 2020
1 parent
37b05bc
commit 62bdbc9
Showing
6 changed files
with
284 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
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{} | ||
|
||
type Client struct { | ||
hub *Hub | ||
conn *websocket.Conn | ||
send chan []byte | ||
} | ||
|
||
func (c *Client) readPump() { | ||
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) writePump() { | ||
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 { | ||
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 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 | ||
|
||
go client.writePump() | ||
go client.readPump() | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
module go-websocket-example | ||
|
||
go 1.15 | ||
|
||
require github.com/gorilla/websocket v1.4.2 // indirect |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= | ||
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package main | ||
|
||
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 (h *Hub) run() { | ||
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) | ||
} | ||
case message := <-h.broadcast: | ||
for client := range h.clients { | ||
select { | ||
case client.send <- message: | ||
default: | ||
close(client.send) | ||
delete(h.clients, client) | ||
} | ||
} | ||
} | ||
} | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<title>Chat Example</title> | ||
<script type="text/javascript"> | ||
window.onload = function () { | ||
var conn; | ||
var msg = document.getElementById("msg"); | ||
var log = document.getElementById("log"); | ||
|
||
function appendLog(item) { | ||
var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1; | ||
log.appendChild(item); | ||
if (doScroll) { | ||
log.scrollTop = log.scrollHeight - log.clientHeight; | ||
} | ||
} | ||
|
||
document.getElementById("form").onsubmit = function () { | ||
if (!conn) { | ||
return false; | ||
} | ||
if (!msg.value) { | ||
return false; | ||
} | ||
conn.send(msg.value); | ||
msg.value = ""; | ||
return false; | ||
}; | ||
|
||
if (window["WebSocket"]) { | ||
conn = new WebSocket("ws://" + document.location.host + "/ws"); | ||
conn.onclose = function (evt) { | ||
var item = document.createElement("div"); | ||
item.innerHTML = "<b>Connection closed.</b>"; | ||
appendLog(item); | ||
}; | ||
conn.onmessage = function (evt) { | ||
var messages = evt.data.split('\n'); | ||
for (var i = 0; i < messages.length; i++) { | ||
var item = document.createElement("div"); | ||
item.innerText = messages[i]; | ||
appendLog(item); | ||
} | ||
}; | ||
} else { | ||
var item = document.createElement("div"); | ||
item.innerHTML = "<b>Your browser does not support WebSockets.</b>"; | ||
appendLog(item); | ||
} | ||
}; | ||
</script> | ||
<style type="text/css"> | ||
html { | ||
overflow: hidden; | ||
} | ||
|
||
body { | ||
overflow: hidden; | ||
padding: 0; | ||
margin: 0; | ||
width: 100%; | ||
height: 100%; | ||
background: gray; | ||
} | ||
|
||
#log { | ||
background: white; | ||
margin: 0; | ||
padding: 0.5em 0.5em 0.5em 0.5em; | ||
position: absolute; | ||
top: 0.5em; | ||
left: 0.5em; | ||
right: 0.5em; | ||
bottom: 3em; | ||
overflow: auto; | ||
} | ||
|
||
#form { | ||
padding: 0 0.5em 0 0.5em; | ||
margin: 0; | ||
position: absolute; | ||
bottom: 1em; | ||
left: 0px; | ||
width: 100%; | ||
overflow: hidden; | ||
} | ||
|
||
</style> | ||
</head> | ||
<body> | ||
<div id="log"></div> | ||
<form id="form"> | ||
<input type="submit" value="Send" /> | ||
<input type="text" id="msg" size="64" autofocus /> | ||
</form> | ||
</body> | ||
</html> |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package main | ||
|
||
import ( | ||
"flag" | ||
"log" | ||
"net/http" | ||
) | ||
|
||
var addr = flag.String("addr", ":8080", "http service address") | ||
|
||
func serveIndex(w http.ResponseWriter, r *http.Request) { | ||
log.Println(r.URL) | ||
if r.URL.Path != "/" { | ||
http.Error(w, "Not found", http.StatusNotFound) | ||
return | ||
} | ||
if r.Method != "GET" { | ||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) | ||
return | ||
} | ||
http.ServeFile(w, r, "index.html") | ||
} | ||
|
||
func main() { | ||
flag.Parse() | ||
hub := newHub() | ||
go hub.run() | ||
http.HandleFunc("/", serveIndex) | ||
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { | ||
serveWs(hub, w, r) | ||
}) | ||
err := http.ListenAndServe(*addr, nil) | ||
if err != nil { | ||
log.Fatal("Liatend and serve: ", err) | ||
} | ||
} |