From 6962cf4989edd639c7377c094c08a2dce7316e29 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Tue, 11 Jul 2023 10:40:31 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20server=20=E5=8C=85=20websocket=20?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=99=A8=E6=94=AF=E6=8C=81=E5=8E=8B=E7=BC=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/options.go | 47 +++++++++++++++++++++++++++++++++++++---------- server/server.go | 5 ++++- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/server/options.go b/server/options.go index 14af5b4..15b5166 100644 --- a/server/options.go +++ b/server/options.go @@ -30,16 +30,43 @@ type option struct { } type runtime struct { - id int64 // 服务器id - cross map[string]Cross // 跨服 - deadlockDetect time.Duration // 是否开启死锁检测 - supportMessageTypes map[int]bool // websocket模式下支持的消息类型 - certFile, keyFile string // TLS文件 - messagePoolSize int // 消息池大小 - messageChannelSize int // 消息通道大小 - prod bool // 是否为生产模式 - ticker *timer.Ticker // 定时器 - websocketReadDeadline time.Duration // websocket连接超时时间 + id int64 // 服务器id + cross map[string]Cross // 跨服 + deadlockDetect time.Duration // 是否开启死锁检测 + supportMessageTypes map[int]bool // websocket模式下支持的消息类型 + certFile, keyFile string // TLS文件 + messagePoolSize int // 消息池大小 + messageChannelSize int // 消息通道大小 + prod bool // 是否为生产模式 + ticker *timer.Ticker // 定时器 + websocketReadDeadline time.Duration // websocket连接超时时间 + websocketCompression int // websocket压缩等级 + websocketWriteCompression bool // websocket写入压缩 +} + +// WithWebsocketWriteCompression 通过数据写入压缩的方式创建Websocket服务器 +// - 默认不开启数据压缩 +func WithWebsocketWriteCompression() Option { + return func(srv *Server) { + if srv.network != NetworkWebsocket { + return + } + srv.websocketWriteCompression = true + } +} + +// WithWebsocketCompression 通过数据压缩的方式创建Websocket服务器 +// - 默认不开启数据压缩 +func WithWebsocketCompression(level int) Option { + return func(srv *Server) { + if srv.network != NetworkWebsocket { + return + } + if !(-2 <= level && level <= 9) { + panic("websocket: invalid compression level") + } + srv.websocketCompression = level + } } // WithMessageChannelSize 通过指定消息通道大小的方式创建服务器 diff --git a/server/server.go b/server/server.go index bcc1654..1317f74 100644 --- a/server/server.go +++ b/server/server.go @@ -250,7 +250,10 @@ func (slf *Server) Run(addr string) error { ip = addr[0:index] } } - + if slf.websocketCompression > 0 { + _ = ws.SetCompressionLevel(slf.websocketCompression) + } + ws.EnableWriteCompression(slf.websocketWriteCompression) conn := newWebsocketConn(slf, ws, ip) for k, v := range request.URL.Query() { if len(v) == 1 {