GO-WebSockets客户端实现方法

该博客介绍了如何使用Go语言中的gorilla/websocket库创建WebSocket客户端管理器,包括构造函数、连接服务端、发送和接收消息的线程以及重连机制。示例代码展示了如何初始化、启动客户端以及处理错误和消息收发。
摘要由CSDN通过智能技术生成

使用到的包:github.com/gorilla/websocket

package main

import (
    "fmt"
    "github.com/gorilla/websocket"
    "log"
    "net/url"
    "sync"
    "time"
)

type websocketClientManager struct {
    conn        *websocket.Conn
    addr        *string
    path        string
    sendMsgChan chan string
    recvMsgChan chan string
    isAlive     bool
    timeout     int
}

// 构造函数
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: "ws", Host: *wsc.addr, Path: wsc.path}
    log.Printf("connecting to %s", u.String())
    wsc.conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
    if err != nil {
        fmt.Println(err)
        return

    }
    wsc.isAlive = true
    log.Printf("connecting to %s 链接成功!!!", u.String())

}

// 发送消息
func (wsc *websocketClientManager) sendMsgThread() {
    go func() {
        for {
            msg := <-wsc.sendMsgChan
            err := wsc.conn.WriteMessage(websocket.TextMessage, []byte(msg))
            if err != nil {
                log.Println("write:", err)
                continue
            }
        }
    }()
}

// 读取消息
func (wsc *websocketClientManager) readMsgThread() {
    go func() {
        for {
            if wsc.conn != nil {
                _, message, err := wsc.conn.ReadMessage()
                if err != nil {
                    log.Println("read:", err)
                    wsc.isAlive = false
                    // 出现错误,退出读取,尝试重连
                    break
                }
                log.Printf("recv: %s", message)
                // 需要读取数据,不然会阻塞
                wsc.recvMsgChan <- string(message)
            }

        }
    }()
}

// 开启服务并重连
func (wsc *websocketClientManager) start() {
    for {
        if wsc.isAlive == false {
            wsc.dail()
            wsc.sendMsgThread()
            wsc.readMsgThread()
        }
        time.Sleep(time.Second * time.Duration(wsc.timeout))
    }
}

func main() {
    wsc := NewWsClientManager("192.168.12.15", "10086", "/v1", 10)
    wsc.start()
    var w1 sync.WaitGroup
    w1.Add(1)
    w1.Wait()
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值