- Constants
- Variables
- Conn">type Conn
- CloseError">type CloseError
- Dialer">type Dialer
- PreparedMessage">type PreparedMessage
- Upgrader">type Upgrader
- 举例
文档:https://godoc.org/github.com/gorilla/websocket
Constants
const (
CloseNormalClosure = 1000
CloseGoingAway = 1001
CloseProtocolError = 1002
CloseUnsupportedData = 1003
CloseNoStatusReceived = 1005
CloseAbnormalClosure = 1006
CloseInvalidFramePayloadData = 1007
ClosePolicyViolation = 1008
CloseMessageTooBig = 1009
CloseMandatoryExtension = 1010
CloseInternalServerErr = 1011
CloseServiceRestart = 1012
CloseTryAgainLater = 1013
CloseTLSHandshake = 1015
)
Variables
// 默认拨号器
var DefaultDialer = &Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 45 * time.Second,
}
// 握手失败错误
var ErrBadHandshake = errors.New("websocket: bad handshake")
// 向一个已关闭连接写入消息的错误
var ErrCloseSent = errors.New("websocket: close sent")
// 超出读取限制错误
var ErrReadLimit = errors.New("websocket: read limit exceeded")
func FormatCloseMessage(closeCode int, text string) []byte 格式化为一条关闭消息
func IsCloseError(err error, codes …int) bool err是否为codes中的某个错误
func IsUnexpectedCloseError(err error, expectedCodes …int) bool err是否不为expectedCodes 中的某个错误
func IsWebSocketUpgrade(r *http.Request) bool 判断是否是websocket连接
type Conn
Conn类型表示一个WebSocket连接
type Conn struct {
// contains filtered or unexported fields
}
// 关闭连接
func (c *Conn) Close() error
//返回当前关闭处理程序
func (c *Conn) CloseHandler() func(code int, text string) error
//启用或关闭压缩
func (c *Conn) EnableWriteCompression(enable bool)
// 返回本地网络地址
func (c *Conn) LocalAddr() net.Addr
//返回远程网络地址
func (c *Conn) RemoteAddr() net.Addr
//返回当前ping处理器
func (c *Conn) PingHandler() func(appData string) error
//返回当前pong处理器
func (c *Conn) PongHandler() func(appData string) error
//读取josn消息
func (c *Conn) ReadJSON(v interface{}) error
//读取消息
func (c *Conn) ReadMessage() (messageType int, p []byte, err error)
//设置压缩级别
func (c *Conn) SetCompressionLevel(level int) error
//接收到ping消息后,处理机制,默认返回一个pong
func (c *Conn) SetPingHandler(h func(appData string) error)
//接收到pong消息后,处理机制,默认不处理
func (c *Conn) SetPongHandler(h func(appData string) error)
//设置读取超时
//读取超时后,websocket连接状态被破坏,以后的读取都会返回一个错误
//t的零值表示读取不会超时
func (c *Conn) SetReadDeadline(t time.Time) error
//设置读取最大字节数
//如果消息超过了限制,连接将向对等方发送一条关闭消息,并向应用程序返回ErrReadLimit
func (c *Conn) SetReadLimit(limit int64)
//设置写入超时
//写入超时后,websocket连接状态被破坏,以后的写入都会返回一个错误
//t的零值表示写入不会超时
func (c *Conn) SetWriteDeadline(t time.Time) error
//写入json消息
func (c *Conn) WriteJSON(v interface{}) error
//写入消息
func (c *Conn) WriteMessage(messageType int, data []byte) error
// 写入已准备好的消息
func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error
type CloseError
type CloseError struct {
// Code is defined in RFC 6455, section 11.7.
Code int
// Text is the optional text payload.
Text string
}
func (e *CloseError) Error() string
type Dialer
一个拨号器包含连接到WebSocket服务器的选项
type Dialer struct {
// NetDial指定用于创建TCP连接的拨号函数
NetDial func(network, addr string) (net.Conn, error)
// NetDialContext指定用于创建TCP连接的拨号函数
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
// 设定代理,如果代理是nil或返回nil *URL,则不使用代理
Proxy func(*http.Request) (*url.URL, error)
// TLS配置
TLSClientConfig *tls.Config
// 握手超时
HandshakeTimeout time.Duration
// 读取缓冲区大小
ReadBufferSize, WriteBufferSize int
// 写入缓冲区大小
WriteBufferPool BufferPool
// Subprotocols specifies the client's requested subprotocols.
Subprotocols []string
// 开启压缩标志
EnableCompression bool
// 指定cookieJar
Jar http.CookieJar
}
func (d Dialer) Dial(urlStr string, requestHeader http.Header) (Conn, *http.Response, error)
- 创建一个连接
func (d Dialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (Conn, *http.Response, error)
- 创建一个连接
type PreparedMessage
PreparedMessage缓存在消息有效负载的连线表示上。使用PreparedMessage有效地向多个连接发送消息有效负载。在使用压缩时,PreparedMessage特别有用,因为CPU和内存昂贵的压缩操作可以对给定的一组压缩选项执行一次
type PreparedMessage struct {
// contains filtered or unexported fields
}
func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error)
type Upgrader
Upgrader指定了将HTTP连接升级为WebSocket连接的参数
type Upgrader struct {
// 握手超时
HandshakeTimeout time.Duration
// 读取缓冲区大小
ReadBufferSize, WriteBufferSize int
// 写入缓冲区大小
WriteBufferPool BufferPool
// Subprotocols specifies the server's supported protocols in order of
// preference. If this field is not nil, then the Upgrade method negotiates a
// subprotocol by selecting the first match in this list with a protocol
// requested by the client. If there's no match, then no protocol is
// negotiated (the Sec-Websocket-Protocol header is not included in the
// handshake response).
Subprotocols []string
// Error specifies the function for generating HTTP error responses. If Error
// is nil, then http.Error is used to generate the HTTP response.
Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
// Origin检测,以防止跨站点请求伪造。
CheckOrigin func(r *http.Request) bool
// 开启压缩标志
EnableCompression bool
}
func (u Upgrader) Upgrade(w http.ResponseWriter, r http.Request, responseHeader http.Header) (*Conn, error) 升级HTTP连接为WebSocket连接
举例
package main
import (
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
)
var upGrader = websocket.Upgrader{
CheckOrigin: func (r *http.Request) bool {
return true
},
}
//webSocket请求ping 返回pong
func ping(c *gin.Context) {
//升级get请求为webSocket协议
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
defer ws.Close()
//读取ws中的数据,一定要,单独write会报错
mt, message, err := ws.ReadMessage()
if err != nil {
return
}
// 一次read多次send
for {
message = []byte("test")
//写入ws数据
err = ws.WriteMessage(mt, message)
if err != nil {
break
}
time.Sleep(time.Second)
}
fmt.Println("wesocket 关闭," + ws.RemoteAddr().String())
}
func main() {
bindAddress := "localhost:2303"
r := gin.Default()
r.GET("/ping", ping)
r.Run(bindAddress)
}