使用到的包: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 := 

文章来源于互联网:GO-WebSockets客户端简单实现

发表评论