websocket客户端

import (
      //省略其他,引用一个第三方库,github有源码,对websokcet的封装
     "github.com/gorilla/websocket"
)

const (
    server = "127.0.0.1:8086"
    serverPath = "/ws"
)

func newConnection() (conn *websocket.Conn,err error){

    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)
    u := url.URL{Scheme: "ws", Host: server, Path: serverPath}
    clientConn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
    if(err != nil){
        log.Printf("newConnection connecting error ", err)
        return nil,err
    }
    return  clientConn,nil
}

//有了connection之后就可以读写数据了
conn.ReadMessage()
conn.WriteMessage(websocket.BinaryMessage,byte data)
conn.WriteMessage(websocket.TextMessage,string data)

你可能感兴趣的:(websocket客户端)