quickws

package module
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 22, 2024 License: Apache-2.0 Imports: 31 Imported by: 9

README

简介

quickws是一个高性能的websocket库

Go codecov Go Report Card

特性

  • 完整实现rfc6455
  • 完整实现rfc7692
  • 高tps
  • 低内存占用
  • 池化管理所有buffer

内容

注意⚠️

quickws默认返回read buffer的浅引用,如果生命周期超过OnMessage的,需要clone一份再使用

Installation

go get github.com/antlabs/quickws

example

net http升级到websocket服务端


package main

import (
 "fmt"
 "net/http"
 "time"

 "github.com/antlabs/quickws"
)

type echoHandler struct{}

func (e *echoHandler) OnOpen(c *quickws.Conn) {
 fmt.Println("OnOpen:\n")
}

func (e *echoHandler) OnMessage(c *quickws.Conn, op quickws.Opcode, msg []byte) {
 fmt.Printf("OnMessage: %s, %v\n", msg, op)
 if err := c.WriteTimeout(op, msg, 3*time.Second); err != nil {
  fmt.Println("write fail:", err)
 }
}

func (e *echoHandler) OnClose(c *quickws.Conn, err error) {
 fmt.Println("OnClose: %v", err)
}

// echo测试服务
func echo(w http.ResponseWriter, r *http.Request) {
 c, err := quickws.Upgrade(w, r, quickws.WithServerReplyPing(),
  // quickws.WithServerDecompression(),
  // quickws.WithServerIgnorePong(),
  quickws.WithServerCallback(&echoHandler{}),
  quickws.WithServerReadTimeout(5*time.Second),
 )
 if err != nil {
  fmt.Println("Upgrade fail:", err)
  return
 }

 c.StartReadLoop()
}

func main() {
 http.HandleFunc("/", echo)

 http.ListenAndServe(":8080", nil)
}

返回

gin升级到websocket服务端

package main

import (
 "fmt"

 "github.com/antlabs/quickws"
 "github.com/gin-gonic/gin"
)

type handler struct{}

func (h *handler) OnOpen(c *quickws.Conn) {
 fmt.Printf("服务端收到一个新的连接")
}

func (h *handler) OnMessage(c *quickws.Conn, op quickws.Opcode, msg []byte) {
 // 如果msg的生命周期不是在OnMessage中结束,需要拷贝一份
 // newMsg := make([]byte, len(msg))
 // copy(newMsg, msg)

 fmt.Printf("收到客户端消息:%s\n", msg)
 c.WriteMessage(op, msg)
 // os.Stdout.Write(msg)
}

func (h *handler) OnClose(c *quickws.Conn, err error) {
 fmt.Printf("服务端连接关闭:%v\n", err)
}

func main() {
 r := gin.Default()
 r.GET("/", func(c *gin.Context) {
  con, err := quickws.Upgrade(c.Writer, c.Request, quickws.WithServerCallback(&handler{}))
  if err != nil {
   return
  }
  con.StartReadLoop()
 })
 r.Run()
}

返回

客户端

package main

import (
 "fmt"
 "time"

 "github.com/antlabs/quickws"
)

type handler struct{}

func (h *handler) OnOpen(c *quickws.Conn) {
 fmt.Printf("客户端连接成功\n")
}

func (h *handler) OnMessage(c *quickws.Conn, op quickws.Opcode, msg []byte) {
 // 如果msg的生命周期不是在OnMessage中结束,需要拷贝一份
 // newMsg := make([]byte, len(msg))
 // copy(newMsg, msg)

 fmt.Printf("收到服务端消息:%s\n", msg)
 c.WriteMessage(op, msg)
 time.Sleep(time.Second)
}

func (h *handler) OnClose(c *quickws.Conn, err error) {
 fmt.Printf("客户端端连接关闭:%v\n", err)
}

func main() {
 c, err := quickws.Dial("ws://127.0.0.1:8080/", quickws.WithClientCallback(&handler{}))
 if err != nil {
  fmt.Printf("连接失败:%v\n", err)
  return
 }

 c.WriteMessage(opcode.Text, []byte("hello"))
 c.ReadLoop()
}

返回

配置函数

客户端配置参数

配置header
func main() {
 quickws.Dial("ws://127.0.0.1:12345/test", quickws.WithClientHTTPHeader(http.Header{
  "h1": "v1",
  "h2":"v2", 
 }))
}

返回

配置握手时的超时时间
func main() {
 quickws.Dial("ws://127.0.0.1:12345/test", quickws.WithClientDialTimeout(2 * time.Second))
}

返回

配置自动回复ping消息
func main() {
 quickws.Dial("ws://127.0.0.1:12345/test", quickws.WithClientReplyPing())
}

返回

配置socks5代理
import(
    "github.com/antlabs/quickws"
 "golang.org/x/net/proxy"
)

func main() {
    quickws.Dial("ws://127.0.0.1:12345", quickws.WithClientDialFunc(func() (quickws.Dialer, error) {
        return proxy.SOCKS5("tcp", "socks5代理服务地址", nil, nil)
    }))
}

返回

配置proxy代理
import(
    "github.com/antlabs/quickws"
)

func main() {

    proxy := func(*http.Request) (*url.URL, error) {
        return url.Parse("http://127.0.0.1:1007")
    }

    quickws.Dial("ws://127.0.0.1:12345", quickws.WithClientProxyFunc(proxy))
}

返回

配置客户端最大读message
func main() {
 // 限制客户端最大服务返回返回的最大包是1024,如果超过这个大小报错
 quickws.Dial("ws://127.0.0.1:12345/test", quickws.WithClientReadMaxMessage(1024))
}

返回

配置客户端压缩和解压消息
func main() {
 quickws.Dial("ws://127.0.0.1:12345/test", quickws.WithClientDecompressAndCompress())
}

返回

配置客户端上下文接管
func main() {
 quickws.Dial("ws://127.0.0.1:12345/test", quickws.WithClientContextTakeover())
}

返回

服务端配置参数

配置服务自动回复ping消息
func main() {
 c, err := quickws.Upgrade(w, r, quickws.WithServerReplyPing())
        if err != nil {
                fmt.Println("Upgrade fail:", err)
                return
        }   
}

返回

配置服务端最大读message
func main() {
 // 配置服务端读取客户端最大的包是1024大小, 超过该值报错
 c, err := quickws.Upgrade(w, r, quickws.WithServerReadMaxMessage(1024))
        if err != nil {
                fmt.Println("Upgrade fail:", err)
                return
        }   
}

返回

配置服务端解压消息
func main() {
 // 配置服务端读取客户端最大的包是1024大小, 超过该值报错
 c, err := quickws.Upgrade(w, r, quickws.WithServerDecompression())
        if err != nil {
                fmt.Println("Upgrade fail:", err)
                return
        }   
}

返回

配置服务端压缩和解压消息
func main() {
 c, err := quickws.Upgrade(w, r, quickws.WithServerDecompressAndCompress())
        if err != nil {
                fmt.Println("Upgrade fail:", err)
                return
        }   
}

返回

配置服务端上下文接管
func main() {
 // 配置服务端读取客户端最大的包是1024大小, 超过该值报错
 c, err := quickws.Upgrade(w, r, quickws.WithServerContextTakeover)
        if err != nil {
                fmt.Println("Upgrade fail:", err)
                return
        }   
}

返回

综合例子

https://github.com/antlabs/quickws-example

常见问题

1.为什么quickws不标榜zero upgrade?

第一:quickws 是基于 std 的方案实现的 websocket 协议。

第二:原因是 zero upgrade 对 websocket 的性能提升几乎没有影响(同步方式),所以 quickws 就没有选择花时间优化 upgrade 过程,

直接基于 net/http, websocket 的协议是整体符合大数定律,一个存活几秒的websocket协议由 upgrade(握手) frame(数据包) frame frame 。。。组成。

所以随着时间的增长, upgrade 对整体的影响接近于0,我们用数字代入下。

A: 代表 upgrade 可能会慢点,但是 frame 的过程比较快,比如基于 net/http 方案的 websocket

upgrade (100ms) frame(10ms) frame(10ms) frame(10ms) avg = 32.5ms

B: 代表主打zero upgrade的库,假如frame的过程处理慢点,

upgrade (90ms) frame(15ms) frame(15ms) frame(15ms) avg = 33.75ms

简单代入下已经证明了,决定 websocket 差距的是 frame 的处理过程,无论是tps还是内存占用 quickws 在实战中也会证明这个点。所以没有必须也不需要在 upgrade 下功夫,常规优化就够了。

2.quickws tps如何

在5800h的cpu上面,tps稳定在47w/s,接近48w/s。比gorilla使用ReadMessage的38.9w/s,快了近9w/s

quickws.1:
1s:357999/s 2s:418860/s 3s:440650/s 4s:453360/s 5s:461108/s 6s:465898/s 7s:469211/s 8s:470780/s 9s:472923/s 10s:473821/s 11s:474525/s 12s:475463/s 13s:476021/s 14s:476410/s 15s:477593/s 16s:477943/s 17s:478038/s
gorilla-linux-ReadMessage.4.1 
1s:271126/s 2s:329367/s 3s:353468/s 4s:364842/s 5s:371908/s 6s:377633/s 7s:380870/s 8s:383271/s 9s:384646/s 10s:385986/s 11s:386448/s 12s:386554/s 13s:387573/s 14s:388263/s 15s:388701/s 16s:388867/s 17s:389383/s
gorilla-linux-UseReader.4.2:
1s:293888/s 2s:377628/s 3s:399744/s 4s:413150/s 5s:421092/s 6s:426666/s 7s:430239/s 8s:432801/s 9s:434977/s 10s:436058/s 11s:436805/s 12s:437865/s 13s:438421/s 14s:438901/s 15s:439133/s 16s:439409/s 17s:439578/s 
gobwas.6:
1s:215995/s 2s:279405/s 3s:302249/s 4s:312545/s 5s:318922/s 6s:323800/s 7s:326908/s 8s:329977/s 9s:330959/s 10s:331510/s 11s:331911/s 12s:332396/s 13s:332418/s 14s:332887/s 15s:333198/s 16s:333390/s 17s:333550/s

3.quickws 流量测试数据如何 ?

在5800h的cpu上面, 同尺寸read buffer(4k), 对比默认用法,quickws在30s处理119GB数据,gorilla处理48GB数据。

  • quickws
quickws.windows.tcp.delay.4x:
Destination: [127.0.0.1]:9000
Interface lo address [127.0.0.1]:0
Using interface lo to connect to [127.0.0.1]:9000
Ramped up to 10000 connections.
Total data sent:     119153.9 MiB (124941915494 bytes)
Total data received: 119594.6 MiB (125404036361 bytes)
Bandwidth per channel: 6.625⇅ Mbps (828.2 kBps)
Aggregate bandwidth: 33439.980↓, 33316.752↑ Mbps
Packet rate estimate: 3174704.8↓, 2930514.7↑ (9↓, 34↑ TCP MSS/op)
Test duration: 30.001 s.
  • gorilla 使用ReadMessage取数据
gorilla-linux-ReadMessage.tcp.delay:
WARNING: Dumb terminal, expect unglorified output.
Destination: [127.0.0.1]:9003
Interface lo address [127.0.0.1]:0
Using interface lo to connect to [127.0.0.1]:9003
Ramped up to 10000 connections.
Total data sent:     48678.1 MiB (51042707521 bytes)
Total data received: 50406.2 MiB (52854715802 bytes)
Bandwidth per channel: 2.771⇅ Mbps (346.3 kBps)
Aggregate bandwidth: 14094.587↓, 13611.385↑ Mbps
Packet rate estimate: 1399915.6↓, 1190593.2↑ (6↓, 45↑ TCP MSS/op)
Test duration: 30 s.

4.内存占用如何 ?

quickws的特色之一是低内存占用。

1w连接的tps测试,1k payload 回写,初始内存占用约122MB, 在240s-260s之后大约86MB,

百万长链接测试

BenchType : BenchEcho
Framework : quickws
TPS : 108143
EER : -118.52
Min : 32.99us
Avg : 92.26ms
Max : 1.03s
TP50 : 48.37ms
TP75 : 53.88ms
TP90 : 215.18ms
TP95 : 430.07ms
TP99 : 502.95ms
Used : 18.49s
Total : 2000000
Success : 2000000
Failed : 0
Conns : 1000000
Concurrency: 10000
Payload : 1024
CPU Min : -520020.80%
CPU Avg : -912.44%
CPU Max : 220653.13%
MEM Min : 8.46G
MEM Avg : 8.47G
MEM Max : 8.47G

Documentation

Overview

Copyright 2021-2024 antlabs. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2021-2024 antlabs. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2021-2024 antlabs. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (
	Continuation = opcode.Continuation
	Text         = opcode.Text
	Binary       = opcode.Binary

	Close = opcode.Close
	Ping  = opcode.Ping
	Pong  = opcode.Pong
)
View Source
const (
	ParseModeBufio parseMode = iota
	ParseModeWindows
)

Variables

View Source
var (
	// conn已经被关闭
	ErrClosed = errors.New("closed")

	ErrWrongStatusCode      = errors.New("Wrong status code")
	ErrUpgradeFieldValue    = errors.New("The value of the upgrade field is not 'websocket'")
	ErrConnectionFieldValue = errors.New("The value of the connection field is not 'upgrade'")
	ErrSecWebSocketAccept   = errors.New("The value of Sec-WebSocketAaccept field is invalid")

	ErrHostCannotBeEmpty   = errors.New("Host cannot be empty")
	ErrSecWebSocketKey     = errors.New("The value of SEC websocket key field is wrong")
	ErrSecWebSocketVersion = errors.New("The value of SEC websocket version field is wrong, not 13")

	ErrHTTPProtocolNotSupported = errors.New("HTTP protocol not supported")

	ErrOnlyGETSupported     = errors.New("error:Only get methods are supported")
	ErrMaxControlFrameSize  = errors.New("error:max control frame size > 125, need <= 125")
	ErrRsv123               = errors.New("error:rsv1 or rsv2 or rsv3 has a value")
	ErrOpcode               = errors.New("error:wrong opcode")
	ErrNOTBeFragmented      = errors.New("error:since control message MUST NOT be fragmented")
	ErrFrameOpcode          = errors.New("error:since all data frames after the initial data frame must have opcode 0.")
	ErrTextNotUTF8          = errors.New("error:text is not utf8 data")
	ErrClosePayloadTooSmall = errors.New("error:close payload too small")
	ErrCloseValue           = errors.New("error:close value is wrong") // close值不对
	ErrEmptyClose           = errors.New("error:close value is empty") // close的值是空的
	ErrWriteClosed          = errors.New("write close")
)
View Source
var ErrDialFuncAndProxyFunc = errors.New("dialFunc and proxyFunc can't be set at the same time")
View Source
var (
	ErrNotFoundHijacker = errors.New("not found Hijacker")
)
View Source
var (
	ErrUnexpectedFlateStream = errors.New("quickws: internal error, unexpected bytes at end of flate stream")
)

Functions

func StringToBytes

func StringToBytes(s string) []byte

Types

type Callback

type Callback interface {
	OnOpen(*Conn)
	OnMessage(*Conn, Opcode, []byte)
	OnClose(*Conn, error)
}

type ClientOption

type ClientOption func(*DialOption)

func WithClientBindHTTPHeader added in v0.1.5

func WithClientBindHTTPHeader(h *http.Header) ClientOption

6.获取http header

func WithClientBufioMultipleTimesPayloadSize added in v0.0.11

func WithClientBufioMultipleTimesPayloadSize(mt float32) ClientOption

func WithClientBufioParseMode added in v0.0.9

func WithClientBufioParseMode() ClientOption

func WithClientCallback

func WithClientCallback(cb Callback) ClientOption

1. callback 配置客户端callback

func WithClientCallbackFunc added in v0.1.1

func WithClientCallbackFunc(open OnOpenFunc, m OnMessageFunc, c OnCloseFunc) ClientOption

0. CallbackFunc

func WithClientCompression

func WithClientCompression() ClientOption

4.配置压缩

func WithClientContextTakeover added in v0.1.12

func WithClientContextTakeover() ClientOption

21.1 设置客户端支持上下文接管, 默认不支持上下文接管

func WithClientDecompressAndCompress

func WithClientDecompressAndCompress() ClientOption

22.1配置客户端压缩和解压缩

func WithClientDecompression

func WithClientDecompression() ClientOption

10 配置解压缩

func WithClientDelayWriteInitBufferSize added in v0.1.1

func WithClientDelayWriteInitBufferSize(n int32) ClientOption

15.2 配置延迟包的初始化buffer大小

func WithClientDialFunc added in v0.1.8

func WithClientDialFunc(dialFunc func() (Dialer, error)) ClientOption

18. 配置新的dial函数, 这里可以配置socks5代理地址

func WithClientDialTimeout

func WithClientDialTimeout(t time.Duration) ClientOption

3.配置握手时的timeout

func WithClientDisableBufioClearHack added in v0.0.9

func WithClientDisableBufioClearHack() ClientOption

func WithClientEnableUTF8Check added in v0.0.9

func WithClientEnableUTF8Check() ClientOption

func WithClientHTTPHeader

func WithClientHTTPHeader(h http.Header) ClientOption

2.配置http.Header

func WithClientIgnorePong added in v0.0.9

func WithClientIgnorePong() ClientOption

6 配置忽略pong消息

func WithClientMaxDelayWriteDuration added in v0.1.1

func WithClientMaxDelayWriteDuration(d time.Duration) ClientOption

13. 配置延迟发送 配置延迟最大发送时间

func WithClientMaxDelayWriteNum added in v0.1.1

func WithClientMaxDelayWriteNum(n int32) ClientOption

14.2 配置最大延迟个数.client

func WithClientMaxWindowsBits added in v0.1.12

func WithClientMaxWindowsBits(bits uint8) ClientOption

21.1 设置客户端最大窗口位数,使用上下文接管时,这个参数才有效

func WithClientOnCloseFunc added in v0.1.1

func WithClientOnCloseFunc(onClose func(c *Conn, err error)) ClientOption

17.2 配置客户端OnClose

func WithClientOnMessageFunc

func WithClientOnMessageFunc(cb OnMessageFunc) ClientOption

仅仅配置OnMessae函数

func WithClientProxyFunc added in v0.1.9

func WithClientProxyFunc(proxyFunc func(*http.Request) (*url.URL, error)) ClientOption

19. 配置proxy地址

func WithClientReadMaxMessage added in v0.1.12

func WithClientReadMaxMessage(size int64) ClientOption

22.1 设置客户端最大可以读取的message的大小, 默认没有限制

func WithClientReadTimeout added in v0.1.1

func WithClientReadTimeout(t time.Duration) ClientOption

16.2 .设置客户端读超时时间

func WithClientReplyPing

func WithClientReplyPing() ClientOption

配置自动回应ping frame, 当收到ping, 回一个pong

func WithClientSubprotocols added in v0.1.9

func WithClientSubprotocols(subprotocols []string) ClientOption

20. 设置支持的子协议 20.1 设置客户端支持的子协议

func WithClientTCPDelay

func WithClientTCPDelay() ClientOption

2. 设置TCP_NODELAY 设置客户端TCP_NODELAY

func WithClientTLSConfig

func WithClientTLSConfig(tls *tls.Config) ClientOption

1.配置tls.config

func WithClientWindowsMultipleTimesPayloadSize added in v0.0.9

func WithClientWindowsMultipleTimesPayloadSize(mt float32) ClientOption

func WithClientWindowsParseMode added in v0.0.9

func WithClientWindowsParseMode() ClientOption

默认使用窗口解析方式, 以后以后默认解析方式改变过,才有必要使用这个选项

type CloseErrMsg

type CloseErrMsg struct {
	Code StatusCode
	Msg  string
}

func (CloseErrMsg) Error

func (c CloseErrMsg) Error() string

type Config

type Config struct {
	deflate.PermessageDeflateConf // 静态配置, 从WithXXX函数中获取
	// contains filtered or unexported fields
}

Config的配置,有两个种用法 一种是声明一个全局的配置,后面不停使用。 另外一种是局部声明一个配置,然后使用WithXXX函数设置配置

type Conn

type Conn struct {
	Callback // callback移至conn中

	*Config // config 可能是全局,也可能是局部初始化得来的
	// contains filtered or unexported fields
}

func Dial

func Dial(rawUrl string, opts ...ClientOption) (*Conn, error)

https://datatracker.ietf.org/doc/html/rfc6455#section-4.1 又是一顿if else, 咬文嚼字

func DialConf added in v0.0.9

func DialConf(rawUrl string, conf *DialOption) (*Conn, error)

func Upgrade

func Upgrade(w http.ResponseWriter, r *http.Request, opts ...ServerOption) (c *Conn, err error)

func (*Conn) Close

func (c *Conn) Close() (err error)

func (*Conn) NetConn added in v0.1.6

func (c *Conn) NetConn() net.Conn

返回标准库的net.Conn

func (*Conn) ReadLoop

func (c *Conn) ReadLoop() (err error)

func (*Conn) SetWriteDeadline added in v0.1.1

func (c *Conn) SetWriteDeadline(t time.Time) error

func (*Conn) StartReadLoop

func (c *Conn) StartReadLoop()

func (*Conn) WriteCloseTimeout

func (c *Conn) WriteCloseTimeout(sc StatusCode, t time.Duration) (err error)

func (*Conn) WriteControl added in v0.0.9

func (c *Conn) WriteControl(op Opcode, data []byte) (err error)

func (*Conn) WriteMessage

func (c *Conn) WriteMessage(op Opcode, writeBuf []byte) (err error)

func (*Conn) WriteMessageDelay added in v0.0.12

func (c *Conn) WriteMessageDelay(op Opcode, writeBuf []byte) (err error)

func (*Conn) WritePing added in v0.0.9

func (c *Conn) WritePing(data []byte) (err error)

data 不能超过125字节, rfc规定

func (*Conn) WritePong added in v0.0.9

func (c *Conn) WritePong(data []byte) (err error)

data 不能超过125字节, rfc规定

func (*Conn) WriteTimeout

func (c *Conn) WriteTimeout(op Opcode, data []byte, t time.Duration) (err error)

type ConnOption

type ConnOption struct {
	Config
}

type DefCallback

type DefCallback struct{}

func (*DefCallback) OnClose

func (defcallback *DefCallback) OnClose(_ *Conn, _ error)

func (*DefCallback) OnMessage

func (defcallback *DefCallback) OnMessage(_ *Conn, _ Opcode, _ []byte)

func (*DefCallback) OnOpen

func (defcallback *DefCallback) OnOpen(_ *Conn)

type DialOption

type DialOption struct {
	Header http.Header

	Config
	// contains filtered or unexported fields
}

func ClientOptionToConf added in v0.0.9

func ClientOptionToConf(opts ...ClientOption) *DialOption

func (*DialOption) Dial

func (d *DialOption) Dial() (wsCon *Conn, err error)

type Dialer added in v0.1.8

type Dialer interface {
	Dial(network, addr string) (c net.Conn, err error)
}

握手

type DialerTimeout added in v0.2.1

type DialerTimeout interface {
	DialTimeout(network, addr string, timeout time.Duration) (c net.Conn, err error)
}

带超时时间的握手

type OnCloseFunc added in v0.1.1

type OnCloseFunc func(*Conn, error)

只设置OnClose, 和OnMessage互斥

func (OnCloseFunc) OnClose added in v0.1.1

func (o OnCloseFunc) OnClose(c *Conn, err error)

func (OnCloseFunc) OnMessage added in v0.1.1

func (o OnCloseFunc) OnMessage(_ *Conn, _ Opcode, _ []byte)

func (OnCloseFunc) OnOpen added in v0.1.1

func (o OnCloseFunc) OnOpen(_ *Conn)

type OnMessageFunc

type OnMessageFunc func(*Conn, Opcode, []byte)

只设置OnMessage, 和OnClose互斥

func (OnMessageFunc) OnClose

func (o OnMessageFunc) OnClose(_ *Conn, _ error)

func (OnMessageFunc) OnMessage

func (o OnMessageFunc) OnMessage(c *Conn, op Opcode, data []byte)

func (OnMessageFunc) OnOpen

func (o OnMessageFunc) OnOpen(_ *Conn)

type OnOpenFunc added in v0.1.1

type OnOpenFunc func(*Conn)

type Opcode

type Opcode = opcode.Opcode

type ServerOption

type ServerOption func(*ConnOption)

func WithServerBufioMultipleTimesPayloadSize added in v0.0.11

func WithServerBufioMultipleTimesPayloadSize(mt float32) ServerOption

12 配置多倍payload缓冲区, 1.是1024 2。是2048 为何不让用户自己配置呢,可以和底层的buffer池结合起来,/1024就知道命中哪个缓冲区了, 不需要维护index命中的哪个sync.Pool 如果用户传些奇奇怪怪的数字,就不好办了

func WithServerBufioParseMode added in v0.0.9

func WithServerBufioParseMode() ServerOption
9.

使用基于bufio的解析方式

func WithServerCallback

func WithServerCallback(cb Callback) ServerOption

配置服务端回调函数

func WithServerCallbackFunc added in v0.1.1

func WithServerCallbackFunc(open OnOpenFunc, m OnMessageFunc, c OnCloseFunc) ServerOption

配置服务端回调函数

func WithServerContextTakeover added in v0.1.12

func WithServerContextTakeover() ServerOption

21.2 设置服务端支持上下文接管, 默认不支持上下文接管

func WithServerDecompressAndCompress

func WithServerDecompressAndCompress() ServerOption

22.2配置服务端压缩和解压缩

func WithServerDecompression

func WithServerDecompression() ServerOption

func WithServerDelayWriteInitBufferSize added in v0.0.12

func WithServerDelayWriteInitBufferSize(n int32) ServerOption

15.1 配置延迟包的初始化buffer大小

func WithServerDisableBufioClearHack added in v0.0.9

func WithServerDisableBufioClearHack() ServerOption

11 关闭bufio clear hack优化

func WithServerEnableUTF8Check added in v0.0.9

func WithServerEnableUTF8Check() ServerOption

3.关闭utf8检查

func WithServerIgnorePong

func WithServerIgnorePong() ServerOption

func WithServerMaxDelayWriteDuration added in v0.0.12

func WithServerMaxDelayWriteDuration(d time.Duration) ServerOption

13. 配置延迟发送 配置延迟最大发送时间

func WithServerMaxDelayWriteNum added in v0.0.12

func WithServerMaxDelayWriteNum(n int32) ServerOption

14.1 配置最大延迟个数.server

func WithServerMaxWindowBits added in v0.1.12

func WithServerMaxWindowBits(bits uint8) ServerOption

22.2 设置服务端最大窗口位数, 使用上下文接管时,这个参数才有效

func WithServerOnCloseFunc added in v0.1.1

func WithServerOnCloseFunc(onClose func(c *Conn, err error)) ServerOption

17。 只配置OnClose 17.1 配置服务端OnClose

func WithServerOnMessageFunc

func WithServerOnMessageFunc(cb OnMessageFunc) ServerOption

4.仅仅配置OnMessae函数 仅仅配置OnMessae函数

func WithServerReadMaxMessage added in v0.1.12

func WithServerReadMaxMessage(size int64) ServerOption

22.2 设置服务端最大可以读取的message的大小,默认没有限制

func WithServerReadTimeout

func WithServerReadTimeout(t time.Duration) ServerOption

16. 配置读超时时间

16.1 .设置服务端读超时时间

func WithServerReplyPing

func WithServerReplyPing() ServerOption

5. 配置自动回应ping frame, 当收到ping, 回一个pong

func WithServerSubprotocols added in v0.1.6

func WithServerSubprotocols(subprotocols []string) ServerOption

20.2 设置服务端支持的子协议

func WithServerTCPDelay

func WithServerTCPDelay() ServerOption

设置TCP_NODELAY 为false, 开启nagle算法 设置服务端TCP_NODELAY

func WithServerWindowsMultipleTimesPayloadSize added in v0.0.9

func WithServerWindowsMultipleTimesPayloadSize(mt float32) ServerOption

7. 设置几倍payload的缓冲区 只有解析方式是窗口的时候才有效 如果为1.0就是1024 + 14, 如果是2.0就是2048 + 14

func WithServerWindowsParseMode added in v0.0.9

func WithServerWindowsParseMode() ServerOption

8 配置windows解析方式 默认使用窗口解析方式, 以后以后默认解析方式改变过,才有必要使用这个选项

type StatusCode

type StatusCode int16

https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1 这里记录了各种状态码的含义

const (
	// NormalClosure 正常关闭
	NormalClosure StatusCode = 1000
	// EndpointGoingAway 对端正在消失
	EndpointGoingAway StatusCode = 1001
	// ProtocolError 表示对端由于协议错误正在终止连接
	ProtocolError StatusCode = 1002
	// DataCannotAccept 收到一个不能接受的数据类型
	DataCannotAccept StatusCode = 1003
	// NotConsistentMessageType 表示对端正在终止连接, 消息类型不一致
	NotConsistentMessageType StatusCode = 1007
	// TerminatingConnection 表示对端正在终止连接, 没有好用的错误, 可以用这个错误码表示
	TerminatingConnection StatusCode = 1008
	// TooBigMessage  消息太大, 不能处理, 关闭连接
	TooBigMessage StatusCode = 1009
	// NoExtensions 只用于客户端, 服务端返回扩展消息
	NoExtensions StatusCode = 1010
	// ServerTerminating 服务端遇到意外情况, 中止请求
	ServerTerminating StatusCode = 1011
)

func (StatusCode) Error added in v0.1.12

func (s StatusCode) Error() string

func (StatusCode) String

func (s StatusCode) String() string

type UpgradeServer

type UpgradeServer struct {
	// contains filtered or unexported fields
}

func NewUpgrade

func NewUpgrade(opts ...ServerOption) *UpgradeServer

func (*UpgradeServer) Upgrade

func (u *UpgradeServer) Upgrade(w http.ResponseWriter, r *http.Request) (c *Conn, err error)

func (*UpgradeServer) UpgradeV2 added in v0.2.2

func (u *UpgradeServer) UpgradeV2(w http.ResponseWriter, r *http.Request, cb Callback) (c *Conn, err error)

Directories

Path Synopsis
autobahn

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL