package conn import ( "github.com/gorilla/websocket" "io" "time" ) // WSConn 封装 websocket.Conn 并实现所有 net.Conn 接口 // 兼容所有使用 net.Conn 的方法 type WSConn struct { *websocket.Conn } // NewWSConn 新建wsConn func NewWSConn(conn *websocket.Conn) *WSConn { return &WSConn{Conn: conn} } // Read reads data from the connection. // Read can be made to time out and return an Error with Timeout() == true // after a fixed time limit; see SetDeadline and SetReadDeadline. func (c *WSConn) Read(b []byte) (int, error) { _, r, err := c.NextReader() if err != nil { return 0, err } n, err := r.Read(b) if err != nil && err != io.EOF { return n, err } return n, nil } // Write writes data to the connection. // Write can be made to time out and return an Error with Timeout() == true // after a fixed time limit; see SetDeadline and SetWriteDeadline. func (c *WSConn) Write(b []byte) (int, error) { err := c.WriteMessage(websocket.BinaryMessage, b) if err != nil { return 0, err } return len(b), nil } // SetDeadline sets the read and write deadlines associated // with the connection. It is equivalent to calling both // SetReadDeadline and SetWriteDeadline. // // A deadline is an absolute time after which I/O operations // fail with a timeout (see type Error) instead of // blocking. The deadline applies to all future and pending // I/O, not just the immediately following call to Read or // Write. After a deadline has been exceeded, the connection // can be refreshed by setting a deadline in the future. // // An idle timeout can be implemented by repeatedly extending // the deadline after successful Read or Write calls. // // A zero value for t means I/O operations will not time out. func (c *WSConn) SetDeadline(t time.Time) error { if err := c.SetReadDeadline(t); err != nil { return err } return c.SetWriteDeadline(t) }