使用wss连接而不是ws连接客户端
连接格式为:wss://127.0.0.1:8100
func main() {
wsc := NewWsClientManager("127.0.0.1", "8100", "", 10)
wsc.dail()
}
func NewWsClientManager(addrIp, addrPort, path string, timeout int) *websocketClientManager {
addrString := addrIp + ":" + addrPort
var sendChan = make(chan string, 10)
var recvChan = make(chan string, 10)
var conn *websocket.Conn
return &websocketClientManager{
addr: &addrString,
path: path,
conn: conn,
sendMsgChan: sendChan,
recvMsgChan: recvChan,
isAlive: false,
timeout: timeout,
}
}
// 链接服务端
func (wsc *websocketClientManager) dail() {
var err error
u := url.URL{Scheme: "wss", Host: *wsc.addr, Path: wsc.path}
log.Printf("connecting to %s", u.String())
dialer := websocket.Dialer{TLSClientConfig: &tls.Config{RootCAs: nil, InsecureSkipVerify: true}}
wsc.conn, _, err = dialer.Dial(u.String(), nil)
if err != nil {
fmt.Println(err)
return
}
wsc.isAlive = true
log.Printf("connecting to %s 链接成功!!!", u.String())
wsc.conn.Close()
}
不断想要接收从服务器端接收数据方法
send := SendMessage{Type: 1}
// 构建json数据
marshal, err := json.Marshal(send)
if err != nil {
fmt.Println(err)
}
// 发送消息
err = wsc.conn.WriteMessage(websocket.TextMessage, marshal)
if err != nil {
fmt.Println(err)
return
}
// for每次循环都会接收服务端的数据,如果接收不到就会堵塞,到接收到为止
//如果只需要接收一次,去掉for循环就可以了
for{
// 接收消息
_, p, err := wsc.conn.ReadMessage()
if err != nil {
}
readMessage= ReadMessage{}
err = json.Unmarshal(p, &readMessage)
if err != nil {
}
//在此处处理接收到的数据
}