Исправлена гонка записи в сокет

This commit is contained in:
set
2026-03-14 21:16:47 +02:00
parent 56a85a436b
commit ef591072f3
4 changed files with 108 additions and 21 deletions

View File

@@ -81,12 +81,12 @@ func processData(data <-chan []byte, connection *connection.Connection) {
response.Put(0x01)
response.Flip()
// Отправляем ответ клиенту
connection.Socket.WriteMessage(websocket.BinaryMessage, response.Bytes())
connection.WriteBinary(response.Bytes())
continue
}
connection.Socket.WriteMessage(websocket.BinaryMessage, []byte{0xFF})
connection.WriteBinary([]byte{0xFF})
logger.LogWarnMessage("failed handshake from " + connection.Socket.RemoteAddr().String() + " because of invalid secret key")
connection.Socket.Close()
connection.Close()
return
}
@@ -111,7 +111,7 @@ func processData(data <-chan []byte, connection *connection.Connection) {
response.PutBytes([]byte(room.RoomID))
response.Flip()
// Отправляем ответ клиенту
connection.Socket.WriteMessage(websocket.BinaryMessage, response.Bytes())
connection.WriteBinary(response.Bytes())
continue
}
@@ -154,7 +154,7 @@ func processData(data <-chan []byte, connection *connection.Connection) {
response.PutBytes(answerBytes)
response.Flip()
// Отправляем ответ клиенту
connection.Socket.WriteMessage(websocket.BinaryMessage, response.Bytes())
connection.WriteBinary(response.Bytes())
continue
}

View File

@@ -1,11 +1,38 @@
package connection
import (
"sync"
"github.com/gorilla/websocket"
)
type Connection struct {
Identificator string
//Подсоединенный сокет
Socket *websocket.Conn
Socket *websocket.Conn
writeMu sync.Mutex
closeMu sync.Mutex
closed bool
}
func (c *Connection) WriteBinary(payload []byte) error {
c.writeMu.Lock()
defer c.writeMu.Unlock()
return c.Socket.WriteMessage(websocket.BinaryMessage, payload)
}
func (c *Connection) WriteJSON(v any) error {
c.writeMu.Lock()
defer c.writeMu.Unlock()
return c.Socket.WriteJSON(v)
}
func (c *Connection) Close() error {
c.closeMu.Lock()
defer c.closeMu.Unlock()
if c.closed {
return nil
}
c.closed = true
return c.Socket.Close()
}