mchess-server/connection/type.go
Marco 26242424ed Implement thread-safe ringbuffer for websocket messages
This implements a ringbuffer that is used to decouple the raw websocket
connection from the messages that the game handler handles.
2023-11-26 21:37:14 +01:00

64 lines
1.2 KiB
Go

package connection
import (
"context"
"nhooyr.io/websocket"
)
type Connection struct {
ws *websocket.Conn
ctx context.Context
buffer MessageBuffer
}
func NewConnection(options ...func(*Connection)) *Connection {
connection := Connection{
buffer: *newMessageBuffer(100),
}
for _, option := range options {
option(&connection)
}
if connection.ws != nil {
go func() {
for {
_, msg, _ := connection.ws.Read(connection.ctx)
connection.buffer.Insert(string(msg))
}
}()
}
return &connection
}
func WithWebsocket(ws *websocket.Conn) func(*Connection) {
return func(c *Connection) {
c.ws = ws
}
}
func WithContext(ctx context.Context) func(*Connection) {
return func(c *Connection) {
c.ctx = ctx
}
}
func (conn *Connection) Write(ctx context.Context, msg []byte) error {
return conn.ws.Write(ctx, websocket.MessageText, msg)
}
func (conn *Connection) Read(ctx context.Context) ([]byte, error) {
msg, err := conn.buffer.Get()
if err != nil {
return nil, err // Tell game-handler that connection was lost
}
return []byte(msg), err
}
func (conn *Connection) Close(msg string) {
conn.ws.Close(websocket.StatusCode(400), msg)
}