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.
nnet/core/ws.go

69 lines
1.8 KiB
Go

package core
import (
"github.com/gorilla/websocket"
"io"
"time"
)
2 years ago
// WSConn 封装 websocket.Conn 并实现所有 net.Conn 接口
// 兼容所有使用 net.Conn 的方法
2 years ago
type WSConn struct {
*websocket.Conn
}
// newWSConn 新建wsConn
2 years ago
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.
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)
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)
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 {
return err
}
2 years ago
return c.SetWriteDeadline(t)
}