server/protocol.go

66 lines
1.5 KiB
Go

package main
import (
"bitbucket.org/hackerbots/bot"
"code.google.com/p/go.net/websocket"
"errors"
"log"
)
func Negociate(ws *websocket.Conn, id string, width, height float64) (*bot.Config, error) {
var err error
err = websocket.JSON.Send(ws, bot.NewIdRequest(id))
if err != nil {
return nil, errors.New("generic server error")
}
var clientid bot.ClientID
err = websocket.JSON.Receive(ws, &clientid)
if err != nil {
return nil, errors.New("could not parse id")
}
if v, msg := clientid.Valid(); !v {
log.Printf("clientid is invalid: %+v", clientid)
websocket.JSON.Send(
ws,
bot.NewFailure(msg),
)
return nil, errors.New(msg)
}
log.Printf("clientid: %+v", clientid)
gameParam := bot.NewGameParam(width, height)
err = websocket.JSON.Send(ws, gameParam)
if err != nil {
websocket.JSON.Send(ws, bot.NewFailure("generic server error"))
return nil, err
}
log.Printf("gameparam: %+v", gameParam)
switch clientid.Type {
case "robot":
var conf bot.Config
log.Printf("got here?")
for {
log.Printf("%s Waiting for client to send conf ...", id)
err = websocket.JSON.Receive(ws, &conf)
log.Printf("conf received: %+v", conf)
if err != nil {
return nil, err
}
// TODO: verify conf's type
if conf.Stats.Valid() {
_ = websocket.JSON.Send(ws, bot.NewHandshake(id, true))
break
} else {
_ = websocket.JSON.Send(ws, bot.NewHandshake(id, false))
}
}
conf.Name = clientid.Name
return &conf, nil
case "spectator":
return nil, nil
}
return nil, nil
}