A simple WebSocket client and server implementation in Go.
一个简单的 Go WebSocket 客户端和服务器实现。
-
Client / 客户端
- Automatic reconnection with exponential backoff / 自动重连,支持指数退避
- Heartbeat mechanism / 心跳机制
- Concurrent-safe / 并发安全
- Context-based lifecycle management / 基于上下文的生命周期管理
-
Server / 服务器
- Support multiple concurrent connections / 支持多并发连接
- Heartbeat mechanism per connection / 每个连接的心跳机制
- Broadcast to all connections / 广播到所有连接
- Health check endpoint / 健康检查端点
go get github.com/Misaka-10233/wspackage main
import (
"context"
"log"
"time"
"github.com/Misaka-10233/ws"
"github.com/coder/websocket"
)
func main() {
ctx := context.Background()
// Create callback functions / 创建回调函数
callback := ws.CallBack{
OnConnect: func(conn *websocket.Conn) {
log.Println("Connected to server / 已连接到服务器")
},
OnDisconnect: func(conn *websocket.Conn) {
log.Println("Disconnected from server / 与服务器断开连接")
},
}
// Create WebSocket client / 创建 WebSocket 客户端
client := ws.NewWsClient("ws://localhost:8080/ws", ctx, callback,
ws.ClientWithHeartbeatInterval(5*time.Second), // Heartbeat interval / 心跳间隔
ws.ClientWithWriteTimeout(1*time.Second), // Write timeout / 写入超时
)
// Get message channel / 获取消息通道
msgChan := ws.GetClientMsgChan(client)
// Read messages / 读取消息
go func() {
for msg := range msgChan {
log.Printf("Received from %s: %s / 收到来自 %s 的消息: %s",
msg.Addr, string(msg.Data), msg.Addr, string(msg.Data))
}
}()
// Write message / 发送消息
client.Write(websocket.MessageText, []byte("Hello Server / 你好服务器"))
// Keep running / 保持运行
time.Sleep(30 * time.Second)
// Close client / 关闭客户端
client.Close()
}package main
import (
"context"
"log"
"time"
"github.com/Misaka-10233/ws"
"github.com/coder/websocket"
)
func main() {
ctx := context.Background()
// Create callback functions / 创建回调函数
callback := ws.CallBack{
OnConnect: func(conn *websocket.Conn) {
log.Println("Client connected / 客户端已连接")
},
OnDisconnect: func(conn *websocket.Conn) {
log.Println("Client disconnected / 客户端已断开连接")
},
}
// Create WebSocket server / 创建 WebSocket 服务器
server := ws.NewWsServer(":8080", ctx, callback,
ws.ServerWithHeartbeatInterval(5*time.Second), // Heartbeat interval / 心跳间隔
ws.ServerWithWriteTimeout(1*time.Second), // Write timeout / 写入超时
ws.ServerWithMsgChanSize(100), // Message channel size / 消息通道大小
)
// Get message channel / 获取消息通道
msgChan := server.GetMsgChan()
// Read messages / 读取消息
go func() {
for msg := range msgChan {
log.Printf("Received from %s: %s / 收到来自 %s 的消息: %s",
msg.Addr, string(msg.Data), msg.Addr, string(msg.Data))
}
}()
// Run server / 运行服务器
opts := &websocket.AcceptOptions{
// Configure CORS or other options / 配置 CORS 或其他选项
}
log.Println("Server starting... / 服务器启动中...")
if err := server.Run(opts); err != nil {
log.Fatal("Server error / 服务器错误:", err)
}
}type Resp struct {
Addr string // Client address / 客户端地址
Type websocket.MessageType // Message type (Text/Binary) / 消息类型(文本/二进制)
Data []byte // Message data / 消息数据
}type Req struct {
Type websocket.MessageType // Message type / 消息类型
Data []byte // Message data / 消息数据
}type CallBack struct {
OnConnect func(*websocket.Conn) // Called on connection / 连接建立时调用
OnDisconnect func(*websocket.Conn) // Called on disconnection / 连接断开时调用
}const (
StateConnected = iota // Connected / 已连接
StateDisconnected // Disconnected / 已断开
)func NewWsClient(url string, parent context.Context, callBack CallBack, options ...func(*WsClient)) *WsClientCreates a new WebSocket client with automatic reconnection. / 创建支持自动重连的 WebSocket 客户端。
func GetClientMsgChan(wsc *WsClient) chan RespReturns the channel for receiving messages. / 返回用于接收消息的通道。
func (wsc *WsClient) Write(msgType websocket.MessageType, msg []byte)Sends a message to the server. / 向服务器发送消息。
func (wsc *WsClient) GetClientState() StateReturns the current connection state. / 返回当前连接状态。
func (wsc *WsClient) Close()Closes the client and releases resources. / 关闭客户端并释放资源。
func NewWsServer(url string, parent context.Context, callBack CallBack, opts ...func(*WsServer)) *WsServerCreates a new WebSocket server. / 创建新的 WebSocket 服务器。
func (wss *WsServer) Run(opts *websocket.AcceptOptions) errorStarts the server and blocks until shutdown. / 启动服务器并阻塞直到关闭。
func (wss *WsServer) GetMsgChan() chan RespReturns the channel for receiving messages from all clients. / 返回用于接收所有客户端消息的通道。
func (wss *WsServer) GetAllConnections() []stringReturns addresses of all connected clients. / 返回所有已连接客户端的地址。
func (wss *WsServer) WriteTo(addr string, msgType websocket.MessageType, msg []byte)Sends a message to a specific client. / 向指定客户端发送消息。
func (wss *WsServer) WriteToAll(msgType websocket.MessageType, msg []byte)Sends a message to all connected clients. / 向所有已连接客户端发送消息。
| Option / 选项 | Description / 描述 | Default / 默认值 |
|---|---|---|
ClientWithHeartbeatInterval(d) |
Heartbeat interval / 心跳间隔 | 5s |
ClientWithHeartbeatTimeout(d) |
Heartbeat timeout / 心跳超时 | 1s |
ClientWithWriteTimeout(d) |
Write timeout / 写入超时 | 1s |
ClientWithReadTimeout(d) |
Read timeout / 读取超时 | 1s |
ClientWithWriteQueSize(n) |
Write queue size / 写入队列大小 | 16 |
ClientWithMsgChanSize(n) |
Message channel size / 消息通道大小 | 16 |
| Option / 选项 | Description / 描述 | Default / 默认值 |
|---|---|---|
ServerWithHeartbeatInterval(d) |
Heartbeat interval / 心跳间隔 | 5s |
ServerWithHeartbeatTimeout(d) |
Heartbeat timeout / 心跳超时 | 1s |
ServerWithWriteTimeout(d) |
Write timeout / 写入超时 | 1s |
ServerWithWriteQueSize(n) |
Write queue size / 写入队列大小 | 16 |
ServerWithMsgChanSize(n) |
Message channel size / 消息通道大小 | 16 |
When running the server, the following endpoints are available: / 运行服务器时,以下端点可用:
/ws- WebSocket endpoint / WebSocket 端点/health- Health check endpoint (returns HTTP 200) / 健康检查端点(返回 HTTP 200)
MIT License