Files
gomoku/server/network/network.go
T
tiennm99 1b9eec5f7d refactor: rename Go module and copy core pkgs into server/pkg
- Module: github.com/ratel-online/server → github.com/tiennm99/gomoku/server
- Copied core/{log,util/async,util/json,util/strings,model,network,protocol,consts}
  into server/pkg/* (temporary shims until phase-05 replaces protocol/network)
- Rewrote all ratel-online import paths across server/**/*.go
- Trimmed main.go: single -p flag, WS-only on :1999, no TCP/bot/static
- Trimmed network/wss.go: endpoint /gomoku, no static file serving
- Updated Makefile: removed TCP/bot references, port 1999
2026-04-11 12:04:03 +07:00

69 lines
1.8 KiB
Go

package network
import (
"github.com/tiennm99/gomoku/server/pkg/log"
"github.com/tiennm99/gomoku/server/pkg/model"
"github.com/tiennm99/gomoku/server/pkg/network"
"github.com/tiennm99/gomoku/server/pkg/protocol"
"github.com/tiennm99/gomoku/server/pkg/async"
"github.com/tiennm99/gomoku/server/consts"
"github.com/tiennm99/gomoku/server/database"
"github.com/tiennm99/gomoku/server/state"
"time"
)
// Network is interface of all kinds of network.
type Network interface {
Serve() error
}
// handle processes a new connection: wraps it, authenticates within 3 seconds,
// creates a Player, starts the state machine goroutine, and blocks on Listening.
func handle(rwc protocol.ReadWriteCloser) error {
c := network.Wrapper(rwc)
defer func() {
err := c.Close()
if err != nil {
log.Error(err)
}
}()
log.Info("new player connected! ")
authInfo, err := loginAuth(c)
if err != nil {
_ = c.Write(protocol.ErrorPacket(err))
return err
}
player := database.Connected(c, authInfo)
log.Infof("player auth accessed, ip %s, %d:%s\n", player.IP, player.ID, authInfo.Name)
go state.Run(player)
defer player.Offline()
return player.Listening()
}
// loginAuth reads an AuthInfo JSON packet from the connection within 3 seconds.
// If the client doesn't authenticate in time, it returns ErrorsAuthFail.
func loginAuth(c *network.Conn) (*model.AuthInfo, error) {
authChan := make(chan *model.AuthInfo)
defer close(authChan)
async.Async(func() {
packet, err := c.Read()
if err != nil {
log.Error(err)
return
}
authInfo := &model.AuthInfo{}
err = packet.Unmarshal(authInfo)
if err != nil {
log.Error(err)
return
}
authChan <- authInfo
})
select {
case authInfo := <-authChan:
return authInfo, nil
case <-time.After(3 * time.Second):
return nil, consts.ErrorsAuthFail
}
}