golang websocket 客户端订阅

package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"os"
	"os/signal"
	"time"
)

func main() {

	// install signal
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	// connect ws
	ws := `ws://10.1.7.198:3080/agent/client?token=kVa7NM7urYwcMCc5NYJ1IdmP7lsa&uid=meet&version=1.0.0&zone=8&lang=cn&time=53&platform=pc&model=&foundation=&push_id=&ucode=&mac=&etype=0&product_type=&user_tag=meet`
	c, _, err := websocket.DefaultDialer.Dial(ws, nil)
	if err != nil {
		log.Fatal("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\n", message)
		}
	}
	heartbeat := func() {
		timer := time.NewTimer(time.Second * 19)
		keepLive := `{"method": "general.keeplive","id": 1,"params": {"expires": 60,"date": "%s"}}`
		timeNow := time.Now().Format("2006-01-02 15:04:05")
		for {
			<-timer.C
			if _err := c.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(keepLive, timeNow))); _err != nil {
				log.Fatal("ws心跳失败")
				return
			}
		}
	}

	subscribe := func() {
		subscribeMember := `{"method":"notify.attach","id":4,"params":{"nid":"83605254241","items":[{"name":"notify.call.memberStatusChanged","get":true,"update":true}]}}`
		if err_ := c.WriteMessage(websocket.TextMessage, []byte(subscribeMember)); err != nil {
			log.Fatalln("subscribe failed :", err_)
		}
	}

	//接受消息
	go acceptMsg()

	// 心跳
	go heartbeat()

	// 订阅
	go subscribe()

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

原文链接:golang websocket 客户端订阅 - vx_guanchaoguo0 - 博客园

你可能感兴趣的:(golang,websocket)