Strange random behavior when reading data from tcp sockets

12 days ago - Direct link

Hi,

I'm currently developing a MUD and I'm having some strange behavior when processing network messages. My game has the main server loop that reads connections, a goroutine that processes connections, a go routine that processes messages, and a goroutine that runs an instance of a game session. The client uses one main thread to listen to input from the server. The first byte in a network message represents what kind of message is being received, as represented by the constant vars.

The problem that I'm having is that sometimes the client reads a MESSAGE_TYPE_ACTION as a MESSAGE_TYPE_STANDARD. In other words, even though the first byte is 1, it sometimes thinks it's 0? So it appears that randomly, when the server requires input from the client, only sometimes will the user be able to provide input to the client based.

I have no idea why this is happening. I'm assuming every time the SendMessages function writes to the client, the client is working with a fresh byte array, so there shouldn't be any dirty data there (as in left over bytes from the last message received). Anyone have any ideas or suggestions?

const (

// A standard message will simply be printed by the client
MESSAGE_TYPE_STANDARD MessageType = 0
// An action will require input from the client
MESSAGE_TYPE_ACTION MessageType = 1
...
)
type MessageType int

type Server struct {
...
players [string]*mud.Player
messages chan Message
}

type Message struct {
receiver net.Conn
message []byte
}

func EncodeMessage(s string, t MessageType) []byte {
buffer := []byte{t}
buffer = append(buffer, []byte(s)...)
return buffer
}

func (s *Server) Start() {
l, err := net.Listen("tcp", s.port)
if err != nil {
s.logError.Println(err)
return
}
s.logInfo.Println("Server running at: ", s.port)

defer l.Close()

go s.StartGame()
go s.SendMessages()
fmt.Println(s.messages)
for {
...


Go to article →