code: Add server implementation example code

master
ALI Hamza 2019-09-23 19:18:00 +07:00
commit c2bb0098db
No known key found for this signature in database
GPG Key ID: BCA8A46C87798C4C
3 changed files with 108 additions and 0 deletions

@ -0,0 +1,57 @@
package main
import (
"strings"
"time"
"github.com/gorilla/websocket"
)
type message struct {
Sender string `json:"sender"`
Content string `json:"content"`
Date time.Time `json:"date"`
}
func (m message) dispatch() {
for client := range connections {
client.WriteJSON(m)
}
}
var connections = make(map[*websocket.Conn]string)
func sendChatMessage(sender *websocket.Conn, msg string) {
m := message{
Sender: connections[sender],
Content: msg,
Date: time.Now().UTC(),
}
m.dispatch()
}
func handleDisconnection(sender *websocket.Conn) {
m := message{
Sender: "server",
Content: connections[sender] + " has left the chat",
Date: time.Now().UTC(),
}
m.dispatch()
delete(connections, sender)
}
func handleIncomingMessage(sender *websocket.Conn, msg string) {
if _, ok := connections[sender]; !ok {
connections[sender] = strings.TrimSpace(msg)
m := message{
Sender: "server",
Content: msg + " has joined the chat",
Date: time.Now().UTC(),
}
m.dispatch()
return
}
sendChatMessage(sender, msg)
}

@ -0,0 +1,50 @@
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var (
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
func websocketConnection(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Fprintf(w, "Internal server error: %s", err)
fmt.Printf("Internal server error: %s", err)
return
}
defer ws.Close()
ws.WriteMessage(websocket.TextMessage, []byte("nickname"))
for {
_, p, err := ws.ReadMessage()
if err != nil {
handleDisconnection(ws)
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}
msg := string(p)
handleIncomingMessage(ws, msg)
}
}
func main() {
http.HandleFunc("/websocket", websocketConnection)
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":8080", nil)
}

@ -0,0 +1 @@
<p>sawp</p>