You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.8 KiB
Go
69 lines
1.8 KiB
Go
1 year ago
|
package connection
|
||
2 years ago
|
|
||
|
import (
|
||
|
"github.com/gorilla/websocket"
|
||
|
"io"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
2 years ago
|
// WSConn 封装 websocket.Conn 并实现所有 net.Conn 接口
|
||
2 years ago
|
// 兼容所有使用 net.Conn 的方法
|
||
2 years ago
|
type WSConn struct {
|
||
|
*websocket.Conn
|
||
2 years ago
|
}
|
||
|
|
||
1 year ago
|
// NewWSConn 新建wsConn
|
||
|
func NewWSConn(conn *websocket.Conn) *WSConn {
|
||
2 years ago
|
return &WSConn{Conn: conn}
|
||
2 years ago
|
}
|
||
|
|
||
|
// 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.
|
||
2 years ago
|
func (c *WSConn) Read(b []byte) (int, error) {
|
||
|
_, r, err := c.NextReader()
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
n, err := r.Read(b)
|
||
2 years ago
|
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.
|
||
2 years ago
|
func (c *WSConn) Write(b []byte) (int, error) {
|
||
|
err := c.WriteMessage(websocket.BinaryMessage, b)
|
||
2 years ago
|
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.
|
||
2 years ago
|
func (c *WSConn) SetDeadline(t time.Time) error {
|
||
|
if err := c.SetReadDeadline(t); err != nil {
|
||
2 years ago
|
return err
|
||
|
}
|
||
|
|
||
2 years ago
|
return c.SetWriteDeadline(t)
|
||
2 years ago
|
}
|