2023-11-20 00:25:27 +00:00
|
|
|
package connection
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2023-11-26 20:29:14 +00:00
|
|
|
"log"
|
2023-11-20 00:25:27 +00:00
|
|
|
|
|
|
|
"nhooyr.io/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Connection struct {
|
2023-11-26 20:29:14 +00:00
|
|
|
ws *websocket.Conn
|
|
|
|
wsConnectionEstablished chan bool
|
|
|
|
ctx context.Context
|
|
|
|
buffer MessageBuffer
|
2023-11-20 00:25:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewConnection(options ...func(*Connection)) *Connection {
|
|
|
|
connection := Connection{
|
2023-11-26 20:29:14 +00:00
|
|
|
buffer: *newMessageBuffer(100),
|
|
|
|
wsConnectionEstablished: make(chan bool),
|
2023-11-20 00:25:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, option := range options {
|
|
|
|
option(&connection)
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-26 20:29:14 +00:00
|
|
|
func (conn *Connection) HasWebsocketConnection() bool {
|
|
|
|
return conn.ws != nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn *Connection) SetWebsocketConnection(ws *websocket.Conn) {
|
|
|
|
if ws == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
conn.ws = ws
|
|
|
|
|
|
|
|
select {
|
|
|
|
case conn.wsConnectionEstablished <- true:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
_, msg, _ := conn.ws.Read(conn.ctx)
|
|
|
|
conn.buffer.Insert(string(msg))
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn *Connection) Write(msg []byte) error {
|
|
|
|
if conn.ws == nil { //if ws is not yet set, we wait for it
|
|
|
|
<-conn.wsConnectionEstablished
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Writing message: %s", string(msg))
|
|
|
|
return conn.ws.Write(conn.ctx, websocket.MessageText, msg)
|
2023-11-20 00:25:27 +00:00
|
|
|
}
|
|
|
|
|
2023-11-26 20:29:14 +00:00
|
|
|
func (conn *Connection) Read() ([]byte, error) {
|
2023-11-20 00:25:27 +00:00
|
|
|
msg, err := conn.buffer.Get()
|
|
|
|
if err != nil {
|
2023-11-26 20:29:14 +00:00
|
|
|
conn.ws = nil
|
2023-11-20 00:25:27 +00:00
|
|
|
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)
|
2023-11-26 20:29:14 +00:00
|
|
|
conn.ws = nil
|
2023-11-20 00:25:27 +00:00
|
|
|
}
|