Implement basic ws server and client
This commit is contained in:
76
ws-client/main.go
Normal file
76
ws-client/main.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type WSConnection struct {
|
||||
url string
|
||||
conn *websocket.Conn
|
||||
errChan chan error
|
||||
}
|
||||
|
||||
func (ws *WSConnection) readMessage() {
|
||||
log.Printf("Reading messages")
|
||||
for {
|
||||
_, message, err := ws.conn.ReadMessage()
|
||||
if err != nil {
|
||||
ws.errChan <- err
|
||||
return
|
||||
}
|
||||
log.Printf("Received: %s", message)
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *WSConnection) writeMessage(message string) {
|
||||
err := ws.conn.WriteMessage(websocket.TextMessage, []byte(message))
|
||||
if err != nil {
|
||||
log.Printf("Error during message writing: %v", err)
|
||||
ws.errChan <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *WSConnection) handleError() {
|
||||
for {
|
||||
err := <-ws.errChan
|
||||
log.Println("Error during message reading:", err)
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
ws.open()
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *WSConnection) open() {
|
||||
log.Printf("Connecting to %s", ws.url)
|
||||
conn, _, err := websocket.DefaultDialer.Dial(ws.url, nil)
|
||||
if err != nil {
|
||||
log.Println("Error during connection:", err)
|
||||
ws.errChan <- err
|
||||
return
|
||||
}
|
||||
log.Printf("Connected")
|
||||
ws.conn = conn
|
||||
ws.errChan = make(chan error)
|
||||
go ws.readMessage()
|
||||
go ws.handleError()
|
||||
}
|
||||
|
||||
func main() {
|
||||
log.SetFlags(log.Lmicroseconds)
|
||||
|
||||
wsConn := WSConnection{
|
||||
url: "ws://localhost:8080/ws",
|
||||
}
|
||||
wsConn.open()
|
||||
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for timestamp := range ticker.C {
|
||||
wsConn.writeMessage(timestamp.String())
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user