Skip to main content

websocket

· One min read
package main

import (
"fmt"
"golang.org/x/net/websocket"
"net/http"
)

type Server struct {
conns map[*websocket.Conn]bool
}

func NewServer() *Server {
return &Server{
conns: make(map[*websocket.Conn]bool),
}
}

func (s *Server) handleWS(ws *websocket.Conn) {
fmt.Println("new incoming connection from client:", ws.RemoteAddr())
s.conns[ws] = true
s.readLoop(ws)
}

func (s *Server) readLoop(ws *websocket.Conn) {
buf := make([]byte, 1024)
for {
n, err := ws.Read(buf)
if err != nil {
fmt.Println("read error:", err)
continue
}
data := buf[:n]
fmt.Println("received data:", string(data))
ws.Write([]byte("thank you for the msg"))
}
}

func main() {
s := NewServer()
http.Handle("/ws", websocket.Handler(s.handleWS))
http.ListenAndServe(":8911", nil)
}