-
Notifications
You must be signed in to change notification settings - Fork 0
/
Websockets.go
55 lines (45 loc) · 1.31 KB
/
Websockets.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package FlowX
import (
"fmt"
"github.com/gorilla/websocket"
"log"
"net/http"
)
const (
readBufferSize = 1024
writeBufferSize = 1024
)
func CreateWebSocketConnection(url string) (*websocket.Conn, error) {
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
return conn, err
}
func CloseWebSocketConnection(conn *websocket.Conn, closeCode int, closeMessage string) error {
return conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(closeCode, closeMessage))
}
func ReadWebSocketMessage(conn *websocket.Conn) (messageType int, p []byte, err error) {
return conn.ReadMessage()
}
func WriteWebSocketMessage(conn *websocket.Conn, messageType int, data []byte) error {
return conn.WriteMessage(messageType, data)
}
func WebSocketHandler(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Upgrade(w, r, nil, readBufferSize, writeBufferSize)
if err != nil {
log.Printf("Error upgrading to WebSocket connection: %v\n", err)
return
}
defer conn.Close()
for {
messageType, message, err := conn.ReadMessage()
if err != nil {
log.Println("Error reading WebSocket message:", err)
break
}
fmt.Println("Received message:", string(message))
err = conn.WriteMessage(messageType, message)
if err != nil {
log.Println("Error writing WebSocket message:", err)
break
}
}
}