Last active
June 20, 2023 09:00
-
-
Save kehiy/b901808400620a464f6773ef65e0ac7e to your computer and use it in GitHub Desktop.
web socket server in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"net/http" | |
"golang.org/x/net/websocket" | |
) | |
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().Network()) | |
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{ | |
if err == io.EOF{ | |
fmt.Println("EOF err") | |
break | |
} | |
fmt.Println("read error:", err) | |
continue | |
} | |
msg := buf[:n] | |
s.broadCast(msg) | |
} | |
} | |
func (s *Server) broadCast(b []byte) { | |
for ws := range s.conns{ | |
go func(ws *websocket.Conn) { | |
if _, err := ws.Write(b); err != nil { | |
fmt.Println("write error", err) | |
} | |
}(ws) | |
} | |
} | |
func main() { | |
server := NewServer() | |
http.Handle("/ws", websocket.Handler(server.handleWS)) | |
http.ListenAndServe(":3000", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment