-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebSocket_EchoClient.go
64 lines (51 loc) · 1.01 KB
/
WebSocket_EchoClient.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
56
57
58
59
60
61
62
63
64
/*
WebSocket_EchoClient
本代码演示了如何接受服务器发来的数据
启动服务器:
go run WebSocket_EchoServer.go
运行
go run WebSocket_EchoClient.go ws://localhost:20000
*/
package main
import (
"fmt"
"golang.org/x/net/websocket"
"io"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: ", os.Args[0], "ws://host:port")
os.Exit(1)
}
service := os.Args[1]
conn, err := websocket.Dial(service, "", "http://localhost")
checkError(err)
var msg string
for {
// 接收数据
err := websocket.Message.Receive(conn, &msg)
if err != nil {
if err == io.EOF {
// 接受完毕,正常退出
break
}
fmt.Println("Couldn't receive message: " + err.Error())
break
}
fmt.Println("Received from server: " + msg)
// 发回数据
err = websocket.Message.Send(conn, msg)
if err != nil {
fmt.Println("Couldn't return msg")
break
}
}
os.Exit(0)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}