Golang websocket 客户端

Jackey Golang 122 次浏览 , 没有评论

基于:github.com/gorilla/websocket 实现

func main() {
    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)

    ws := "ws://127.0.0.1:8080/ws"
    c, _, err := websocket.DefaultDialer.Dial(ws, nil)
    if err != nil {
        log.Fatalln("dial", err)
    }
    defer c.Close()
    fmt.Println("connect ...")

    acceptMsg := func() {
        for {
            _, message, err := c.ReadMessage()
            if err != nil {
                log.Println("read:", err)
                return
            }
            log.Printf("recv: \n %s \n", message)
        }
    }

    heartbeat := func() {
        for {
            if _err := c.WriteMessage(websocket.PingMessage, nil); _err != nil {
                log.Fatal("ws 心跳失败")
                return
            }
            time.Sleep(5 * time.Second)
        }
    }

    sendMsg := func() {
        for {
            if _err := c.WriteMessage(websocket.TextMessage, []byte("test message")); _err != nil {
                log.Fatal("ws 发送失败")
                return
            }
            time.Sleep(1 * time.Second)
        }
    }

    go acceptMsg()

    go heartbeat()

    go sendMsg()

    select {
    case <-interrupt:
        log.Println("interrupt")
        if err_ := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err_ != nil {
            log.Println("write close:", err)
            return
        }
    }
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Go