websocket

package module
v0.0.0-...-7b0e155 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2024 License: MIT Imports: 13 Imported by: 0

README

Websocket 客户端-服务器

基于github.com/gorilla/websocket实现的websocket客户端-服务器, 为每个Conn开启两个Goroutine(读写协程), 实例代码参考echo

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSendOnClosedConn = errors.New("send message on closed connection")
	ErrMessageTooLong   = errors.New("message too long")
	ErrMessageTooShort  = errors.New("message too short")
)

Functions

func Run

func Run(config *Config, handler Handler) (io.Closer, error)

Types

type Config

type Config struct {
	Tick            bool          // 是否开启定时器
	Addr            string        // ws服务地址
	ReadTimeout     time.Duration // 读超时
	WriteTimeout    time.Duration // 写超时
	MaxMsgSize      int           // 消息体最大长度
	MinMsgSize      int           // 消息体最小长度
	MaxConns        int           // 最大连接数
	ReadBufferSize  int           // 读缓冲区大小
	WriteBufferSize int           // 写缓冲区大小
	CertFile        string        // 证书路径
	KeyFile         string        // 证书密钥路径
}

Config websocket服务配置

type Conn

type Conn interface {
	// GetID 获取唯一ID
	GetID() int64

	// Close 关闭连接
	Close() error

	// SendTextMsg 发送文本消息
	SendTextMsg(...[]byte) error

	// SendBinaryMsg 发送二进制消息
	SendBinaryMsg(...[]byte) error

	// RemoteAddr 获取客户端地址
	RemoteAddr() net.Addr
}

type Handler

type Handler interface {
	// OnMessage 消息处理
	OnMessage(conn Conn, message []byte)

	// OnConnect 连接建立时调用
	OnConnect(conn Conn)

	// OnClose 连接关闭时调用
	OnClose(conn Conn)

	// OnPing 收到PingMessage时调用
	OnPing(conn Conn, pingMessage string)

	// OnTick 定时任务, bool值返回true的话定时器将被终止, 并不可恢复
	OnTick() (time.Duration, bool)

	// GenerateID 生成全局唯一ID
	GenerateID() int64
}

Directories

Path Synopsis
echo
client command
server command

Jump to

Keyboard shortcuts

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