Beispiel #1
0
func (i *GameController) process(connection network.Connection, session string) error {
	message, err := connection.ReadMessage()
	if err != nil {
		return err
	}
	msession := message.GetSession()
	if msession != session {
		return fmt.Errorf("reject message. wait %s, get %s session", session, msession)
	}
	mtype := message.GetType()
	switch mtype {
	case protocol.PingMessageType:
		i.output <- message
		break
	case protocol.GameInputMessageType:
		if i.input != nil {
			message.SetSession(i.player)
			i.input <- message
		}
		break
	case protocol.GamePlayMessageType:
		i.processGamePlay(message.(*protocol.GamePlayMessage))
		break

	default:
		log.Printf("skip message from session %s with type: %s\n", msession, mtype)
		break
	}
	return nil
}
Beispiel #2
0
func processConnection(s *Server, connection network.Connection, session string) {
	user, err := s.api.GetUser(session)
	if user == nil || err != nil {
		return
	}

	complete := false
	notify := make(chan bool, 2)
	output := make(chan protocol.Message, 3)
	go func() {
		log.Printf("write run for session: %s\n", session)
		for message := range output {
			if protocol.GameCompleteMessageType == message.GetType() {
				complete = true
				break
			}
			// rewrite empty
			message.SetSession(session)
			err := connection.WriteMessage(message)
			if err != nil && connection.IsCloseError(err) {
				break
			}
			if err != nil {
				log.Printf("websocket write: %v", err)
			}
		}
		log.Printf("write done for session: %s\n", session)
		notify <- true
	}()

	controller := NewGameController(user.Name, s, output)
	go func() {
		log.Printf("read run for session: %s\n", session)
		for {
			err := controller.process(connection, session)
			if complete {
				break
			}
			if controller.HaveLogicError() {
				break
			}
			if err != nil && connection.IsCloseError(err) {
				break
			}
			if err != nil {
				log.Printf("websocket read: %v", err)
			}
		}
		log.Printf("read done for session: %s\n", session)
		notify <- true

	}()

	<-notify

	controller.Clear()
	connection.Close()
	close(output)
}