mirror of
https://github.com/statbate/special-pancake.git
synced 2026-08-11 03:12:42 +00:00
ping
This commit is contained in:
parent
89418fdbbd
commit
568dd266c9
1 changed files with 40 additions and 7 deletions
47
app/echo.go
47
app/echo.go
|
|
@ -1,6 +1,8 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
|
|
@ -24,29 +26,42 @@ var (
|
||||||
Count chan int
|
Count chan int
|
||||||
Send chan []byte
|
Send chan []byte
|
||||||
Add chan *websocket.Conn
|
Add chan *websocket.Conn
|
||||||
|
Del chan *websocket.Conn
|
||||||
}{
|
}{
|
||||||
Count: make(chan int, 100),
|
Count: make(chan int, 100),
|
||||||
Send: make(chan []byte, 100),
|
Send: make(chan []byte, 100),
|
||||||
Add: make(chan *websocket.Conn, 100),
|
Add: make(chan *websocket.Conn, 100),
|
||||||
|
Del: make(chan *websocket.Conn, 100),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func broadcast() {
|
func broadcast() {
|
||||||
|
ticker := time.NewTicker(30 * time.Second)
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case conn := <-ws.Add:
|
case conn := <-ws.Add:
|
||||||
wsClients[conn] = struct{}{}
|
wsClients[conn] = struct{}{}
|
||||||
|
|
||||||
|
case conn := <-ws.Del:
|
||||||
|
delete(wsClients, conn)
|
||||||
|
|
||||||
case <-ws.Count:
|
case <-ws.Count:
|
||||||
ws.Count <- len(wsClients)
|
ws.Count <- len(wsClients)
|
||||||
|
|
||||||
case message := <-ws.Send:
|
case message := <-ws.Send:
|
||||||
for conn := range wsClients {
|
sendMessage(message)
|
||||||
if err := conn.WriteMessage(1, message); err != nil {
|
|
||||||
conn.Close()
|
case <-ticker.C:
|
||||||
delete(wsClients, conn)
|
sendMessage([]byte("ping"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendMessage(message []byte) {
|
||||||
|
for conn := range wsClients {
|
||||||
|
if err := conn.WriteMessage(1, message); err != nil {
|
||||||
|
conn.Close()
|
||||||
|
delete(wsClients, conn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -56,5 +71,23 @@ func wsHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ws.Add <- conn
|
go readWS(conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readWS(conn *websocket.Conn) {
|
||||||
|
defer conn.Close()
|
||||||
|
|
||||||
|
ws.Add <- conn
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
ws.Del <- conn
|
||||||
|
}()
|
||||||
|
|
||||||
|
for {
|
||||||
|
_, _, err := conn.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("readWS", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue