forked from chanbakjsd/TerraOceanPlugin
go: create base websocket server
parent
e181a09b4b
commit
09073ac4ff
@ -0,0 +1,17 @@
|
||||
package server
|
||||
|
||||
import "github.com/gorilla/websocket"
|
||||
|
||||
var clients = make(map[*websocket.Conn]bool)
|
||||
|
||||
func newSession(who *websocket.Conn) {
|
||||
clients[who] = true
|
||||
}
|
||||
|
||||
func disconnectSession(who *websocket.Conn) {
|
||||
delete(clients, who)
|
||||
}
|
||||
|
||||
func handleIncomingMessage(who *websocket.Conn, msg string) {
|
||||
//TODO
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
}
|
||||
|
||||
func newConnection(w http.ResponseWriter, r *http.Request) {
|
||||
ws, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
fmt.Fprint(w, "You must use the websocket protocol to connect to this endpoint.", err)
|
||||
}
|
||||
defer ws.Close()
|
||||
|
||||
newSession(ws)
|
||||
for {
|
||||
_, p, err := ws.ReadMessage()
|
||||
if err != nil {
|
||||
disconnectSession(ws)
|
||||
break
|
||||
}
|
||||
|
||||
msg := string(p)
|
||||
handleIncomingMessage(ws, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func StartServer(port int, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
|
||||
hostLocation := ":" + strconv.Itoa(port)
|
||||
http.HandleFunc("/ws", newConnection)
|
||||
|
||||
log.Fatal(http.ListenAndServe(hostLocation, nil))
|
||||
}
|
Loading…
Reference in New Issue