鍍金池/ 問答/GO/ golang官方的websocket包調(diào)用read或者write方法之后會自動關(guān)

golang官方的websocket包調(diào)用read或者write方法之后會自動關(guān)閉連接

查看了一下官方實(shí)現(xiàn)里面write方法在結(jié)束的時(shí)候調(diào)用了close方法,但是read沒有。

我對官方這個(gè)實(shí)現(xiàn)非常費(fèi)解,因?yàn)閣ebsocket就是為了長連接而使用的啊,既然發(fā)送或者接收一次消息之后就關(guān)閉,這樣編寫的意圖是什么?

type Conn struct {
    config  *Config
    request *http.Request

    buf *bufio.ReadWriter
    rwc io.ReadWriteCloser

    rio sync.Mutex
    frameReaderFactory
    frameReader

    wio sync.Mutex
    frameWriterFactory

    frameHandler
    PayloadType        byte
    defaultCloseStatus int

    // MaxPayloadBytes limits the size of frame payload received over Conn
    // by Codec's Receive method. If zero, DefaultMaxPayloadBytes is used.
    MaxPayloadBytes int
}

// Read implements the io.Reader interface:
// it reads data of a frame from the WebSocket connection.
// if msg is not large enough for the frame data, it fills the msg and next Read
// will read the rest of the frame data.
// it reads Text frame or Binary frame.
func (ws *Conn) Read(msg []byte) (n int, err error) {
    ws.rio.Lock()
    defer ws.rio.Unlock()
again:
    if ws.frameReader == nil {
        frame, err := ws.frameReaderFactory.NewFrameReader()
        if err != nil {
            return 0, err
        }
        ws.frameReader, err = ws.frameHandler.HandleFrame(frame)
        if err != nil {
            return 0, err
        }
        if ws.frameReader == nil {
            goto again
        }
    }
    n, err = ws.frameReader.Read(msg)
    if err == io.EOF {
        if trailer := ws.frameReader.TrailerReader(); trailer != nil {
            io.Copy(ioutil.Discard, trailer)
        }
        ws.frameReader = nil
        goto again
    }
    return n, err
}

// Write implements the io.Writer interface:
// it writes data as a frame to the WebSocket connection.
func (ws *Conn) Write(msg []byte) (n int, err error) {
    ws.wio.Lock()
    defer ws.wio.Unlock()
    w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType)
    if err != nil {
        return 0, err
    }
    n, err = w.Write(msg)
    w.Close()
    return n, err
}

// Close implements the io.Closer interface.
func (ws *Conn) Close() error {
    err := ws.frameHandler.WriteClose(ws.defaultCloseStatus)
    err1 := ws.rwc.Close()
    if err != nil {
        return err
    }
    return err1
}
回答
編輯回答
獨(dú)白

Write調(diào)用的是w.Close()不是ws.Close()

2017年11月4日 06:21
編輯回答
解夏

樓主問題解決了沒有啊,我初學(xué) golang,也遇到這個(gè)問題。。。

2018年7月9日 19:49