Marco
bb817ad3af
This implements a ringbuffer that is used to decouple the raw websocket connection from the messages that the game handler handles. There is still a problem: Test_MessageBuffer_GetWaitsForNewDataIfOldOneWasAlreadyGotten fails because buf.Get() returns an old value instead of waiting for a new one. This must be fixed. Additionally, the Insert() and Get() methods must be thread-safe at some point. But since Get() blocks when there is no data, there would be a deadlock if I see this right.
49 lines
870 B
Go
49 lines
870 B
Go
package connection
|
|
|
|
import (
|
|
"context"
|
|
|
|
"nhooyr.io/websocket"
|
|
)
|
|
|
|
type Connection struct {
|
|
ws *websocket.Conn
|
|
}
|
|
|
|
func NewConnection(options ...func(*Connection)) *Connection {
|
|
connection := Connection{}
|
|
|
|
for _, option := range options {
|
|
option(&connection)
|
|
}
|
|
|
|
return &connection
|
|
}
|
|
|
|
func WithWebsocket(ws *websocket.Conn) func(*Connection) {
|
|
return func(c *Connection) {
|
|
c.ws = ws
|
|
}
|
|
}
|
|
|
|
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) {
|
|
var msg []byte
|
|
var err error
|
|
for {
|
|
_, msg, err = conn.ws.Read(ctx)
|
|
if err != nil {
|
|
return nil, err // Tell game-handler that connection was lost
|
|
}
|
|
}
|
|
|
|
return msg, err
|
|
}
|
|
|
|
func (conn *Connection) Close(msg string) {
|
|
conn.ws.Close(websocket.StatusCode(400), msg)
|
|
}
|