2019-10-12 14:07:40 +07:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
2019-10-13 03:14:33 +07:00
|
|
|
"strings"
|
2019-10-12 14:07:40 +07:00
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
ReadBufferSize: 1024,
|
|
|
|
WriteBufferSize: 1024,
|
2019-10-13 03:14:33 +07:00
|
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
|
|
return strings.Contains(r.Host, "localhost")
|
|
|
|
},
|
2019-10-12 14:07:40 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
func newConnection(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ws, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
2019-10-13 03:14:33 +07:00
|
|
|
fmt.Fprintf(w, "An error has occured: %s.\n", err)
|
|
|
|
return
|
2019-10-12 14:07:40 +07:00
|
|
|
}
|
|
|
|
defer ws.Close()
|
|
|
|
|
|
|
|
newSession(ws)
|
|
|
|
for {
|
|
|
|
_, p, err := ws.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
disconnectSession(ws)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
msg := string(p)
|
|
|
|
handleIncomingMessage(ws, msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-12 15:49:28 +07:00
|
|
|
func StartServer(port int) {
|
2019-10-12 14:07:40 +07:00
|
|
|
hostLocation := ":" + strconv.Itoa(port)
|
|
|
|
http.HandleFunc("/ws", newConnection)
|
|
|
|
|
|
|
|
log.Fatal(http.ListenAndServe(hostLocation, nil))
|
|
|
|
}
|