Exemplo n.º 1
0
// ConnectPlayer handles connecting a new player to the game
func (s *Server) ConnectPlayer(socket *glue.Socket) {
	// Logging
	log15.Debug("socket connected", "address", socket.RemoteAddr())
	socket.OnClose(func() {
		log15.Debug("socket closed", "address", socket.RemoteAddr())
	})

	// Attempt to allocate free player Slot
	if slot := s.nextSlot(); slot != -1 {
		log15.Info("Accepting new player connection", "slot", slot)
		s.ConnectedPlayers[slot] = &Player{
			Server: s,
			Slot:   slot,
			Socket: socket,
		}
		s.ConnectedPlayers[slot].Socket.OnClose(func() {
			log15.Debug("socket closed", "address", socket.RemoteAddr())
			s.DisconnectPlayer(slot)
		})
		s.NumConnectedPlayers++
		s.ConnectedPlayers[slot].Socket.Write(msg.SConnected)
		s.ConnectedPlayers[slot].Socket.Write(msg.SDisplayMessage + ":Press [SPACEBAR] To Spawn!")
		go s.ConnectedPlayers[slot].ReadLoop()

	} else {
		// No free slots available
		log15.Info("Rejecting new player connection: Server is full!")
		socket.Write(msg.SGameFull)
	}
}
Exemplo n.º 2
0
func main() {

	log.Info("Initialising ObamaPhony REST API..")
	log.Info("*** ObamaPhony REST API Version 0.1.0 loaded ***")

	controllers.Server()
}
// initial ConnPool of pgx
func (pgdb *PostgresDB) InitConnection() error {
	//var pool *pgx.ConnPool
	var err error

	pgdb.Pool, err = pgx.NewConnPool(pgdb.poolConfig)
	if err != nil {
		log.Info("Unable to create connection pool", "error", err)
		os.Exit(1)
	}

	log.Info("database connect sueecss")
	return nil
}
func (pgdb *PostgresDB) RemoveTask(itemNum int32) error {

	commandTag, err := pgdb.Pool.Exec("deleteTask", itemNum)

	if commandTag.RowsAffected() != 1 {
		log.Info("No row found to delete", "error", err)
		return errors.New("No row found to delete")
	}

	return err

}
Exemplo n.º 5
0
func (t *Timer) runTimer() {
	log15.Info("Timer started", "number", t.number, "remaining", t.remaining)
	tt := time.NewTimer(t.remaining)
	for {
		select {
		case <-t.stop:
			log15.Info("Stopping timer", "number", t.number, "remaining", t.remaining)
			t.finished = true
			close(t.C)
			return
		case <-t.pause:
			log15.Info("Pausing timer", "number", t.number, "remaining", t.remaining)
			t.pausedat = time.Now()
			t.remaining -= t.pausedat.Sub(t.startedat)
			tt.Stop()
		case <-t.resume:
			t.startedat = time.Now()
			elapsed := t.startedat.Sub(t.pausedat)
			if elapsed > t.remaining {
				log15.Info("Timer completed (b)", "number", t.number, "remaining", t.remaining)
				t.C <- time.Now().Add(-t.remaining)
				t.finished = true
				return
			}
			log15.Info("Resuming timer", "number", t.number, "remaining", t.remaining, "elapsed", elapsed)
			tt = time.NewTimer(t.remaining - elapsed)
			t.remaining -= elapsed
		case ttt := <-tt.C:
			log15.Info("Timer completed", "number", t.number, "remaining", t.remaining)
			t.C <- ttt
			t.finished = true
			return
		}
	}
}
Exemplo n.º 6
0
func main() {
	log15.Info("Starting Marqit")
	// debug.InstallCtrlCPanic()

	Mkt := market1.NewMarket1()
	Bnk, AKey := bank1.NewBank1()
	log15.Info("Bank created", "admin", AKey)

	Mkt.RegisterBank("the bank", Bnk)
	Mkt.RegisterTrader("t.irrational", irrational.NewIrrational)
	Mkt.RegisterTrader("t.netplayer", netplayer.NewNetPlayer)
	Mkt.SetCount(manager.TraderCfg{Type: "t.irrational", Count: 10}, manager.TraderCfg{Type: "t.netplayer", Count: 1})
	Mkt.SpawnTraders()

	NStocks := 2 + rand.Intn(30)
	log15.Info("Creating stocks", "n", NStocks)
	for i := 0; i <= NStocks; i++ {
		symbol := ""
		sl := 1 + rand.Intn(3)
		for n := 0; n <= sl; n++ {
			symbol += string(byte(65 + rand.Intn(26)))
		}

		s := exchange.Stock{
			Symbol:  exchange.Symbol(symbol),
			Shares:  uint(rand.Int31n(100000)),
			Trading: true,
			Mode:    exchange.M_AUCTION,
		}
		log15.Info("Adding", "symbol", s.Symbol, "shares", s.Shares)
		Mkt.AddStock(s)
	}

	for _, v := range Mkt.List() {
		recip := 2 * (1 + rand.Intn(5))
		log15.Info("Spreading initial", "symbol", v.Symbol, "volume", v.Shares, "recipients", recip)
		NTraders := len(Mkt.Traders())
		for i := 0; i <= recip; i++ {
			act := rand.Intn(NTraders - 1)
			ba := Mkt.Traders()[act].GetAcct()
			log15.Info("Initial", "recipient", ba, "count", uint64(int(v.Shares)/recip))
			Bnk.SetAsset(ba, v.Symbol, uint64(int(v.Shares)/recip))
		}
	}

	for k := range Mkt.Traders() {
		act := Mkt.Traders()[k].GetAcct()
		amt := float32(rand.Int31n(100000))
		log15.Info("Granting funds", "recipient", act, "ammount", amt)
		Bnk.Transfer(bank.Token{Account: bank.BA_Start, PIN: AKey}, amt, act)
	}

	Mkt.Start(10*time.Second, 15*time.Second, 5)
}
Exemplo n.º 7
0
func startGrpcServer() {
	addr := localIP() + ":" + *grpcPort
	log15.Info("starting gRPC echo service", "listen", addr)
	lis, err := net.Listen("tcp", addr)
	if err != nil {
		Log.Crit("failed to listen", "error", err)
		os.Exit(1)
	}

	// Start GRPC server
	s := grpc.NewServer()
	echo.RegisterEchoserviceServer(s, &service{})
	if err := s.Serve(lis); err != nil {
		Log.Error("error serving grpc server", "error", err)
	}
}
Exemplo n.º 8
0
// ReadLoop receives data from the player client
func (p *Player) ReadLoop() {
	for {
		// Wait for available data
		data, err := p.Socket.Read()
		if err != nil {
			// return and release this goroutine if the socket was closed
			if err == glue.ErrSocketClosed {
				return
			}

			log15.Error("read error", "error", err)
			continue
		}

		components := strings.Split(data, ":")
		switch components[0] {
		case msg.CRequestState:
			p.Socket.Write(msg.SNewState + ":" + p.Server.Sim.LatestState)

		case msg.CSpawn:
			if !p.neededComponents(components, 2) {
				break
			}

			if p.Bike != nil && p.Bike.GetState() != "dead" {
				log15.Debug("Player attempted to spawn with existing bike", "bike", p.Bike)
				break
			}

			p.Bike = p.Server.Sim.SpawnGridBike(components[1], components[2])
			p.Socket.Write(msg.SDisplayMessage + ":")

		case msg.CTurn:
			if !p.neededComponents(components, 1) {
				break
			}
			if p.Bike == nil || p.Bike.GetState() != "move" {
				log15.Debug("Player attemped to turn without existing bike", "bike", p.Bike)
				break
			}
			dir := components[1]
			switch dir {
			case "RIGHT":
				p.Bike.SetTurn(0)
			case "DOWN":
				p.Bike.SetTurn(math.Pi / 2)
			case "LEFT":
				p.Bike.SetTurn(math.Pi)
			case "UP":
				p.Bike.SetTurn(3 * math.Pi / 2)
			default:
				log15.Error("invalid TURN argument", "arg", dir)
			}

		// case msg.CBroadcast:
		// 	// Echo the received data to all other clients
		// 	for i := range gs.ConnectedPlayers {
		// 		if gs.ConnectedPlayers[i].Socket.ID() == p.Socket.ID() {
		// 			continue
		// 		}
		// 		gs.ConnectedPlayers[i].Socket.Write(strings.Join(components[1:], ":"))
		// 	}

		default:
			log15.Info("Returning unknown request to the client", "request", data)
			p.Socket.Write(data)
		}
	}
}
Exemplo n.º 9
0
func (c *client) GetAllInto(destination interface {
	Add(interface{}) error
	Count() int
	MaxCreatedAt() time.Time
	MaxUpdatedAt() time.Time
}) (err error) {

	var response ItembaseResponse
	DocumentsReceived := 0

	err = c.api.Call("GET", c.url, c.auth, nil, c.params, &response)
	if err != nil {
		return
	}

	for _, document := range response.Documents {
		if destination.Add != nil {
			err = destination.Add(document)
			if err != nil {
				log.Info("Error when adding document", "error", err)
			}
		}
	}

	log.Debug("Documents", "found", response.NumDocumentsFound)
	log.Debug("Documents", "returned", response.NumDocumentsReturned)

	if response.NumDocumentsFound == response.NumDocumentsReturned {
		log.Debug("same amount of documents that were found as returned")
		return
	} else {
		DocumentsReceived = response.NumDocumentsReturned
		TotalDocuments := response.NumDocumentsFound
		log.Debug("expecting to receive", "NumDocumentsFound", response.NumDocumentsFound)

		for DocumentsReceived < TotalDocuments {

			log.Debug("expecting", "TotalDocuments", TotalDocuments)

			if c.max > 0 {
				log.Debug("Max", "max", c.max)
				if DocumentsReceived >= c.max {
					log.Debug("Max is reached", "DocumentsReceived", DocumentsReceived)
					return
				}
			}

			if _, ok := c.params["created_at_from"]; ok {
				if c.params["created_at_from"] == destination.MaxCreatedAt().Format(time.RFC3339) {
					log.Error("created_at_from equals to previous created_at_from - We got a loop?", "created_at_from", c.params["created_at_from"])
					return
				}
			}

			c = c.clientWithNewParam("start_at_document", DocumentsReceived)
			err = c.api.Call("GET", c.url, c.auth, nil, c.params, &response)

			if err != nil {
				log.Error("Error when retrieving paginated results", "error", err)
			}

			log.Debug("Documents", "found", response.NumDocumentsFound)
			log.Debug("Documents", "returned", response.NumDocumentsReturned)

			if len(response.Documents) == 0 {
				log.Debug("no documents in response", "response.Documents", len(response.Documents))
				return
			}

			for _, document := range response.Documents {
				if destination.Add != nil {
					destination.Add(document)
					if err != nil {
						log.Info("Error when adding document", "error", err)
					}
				}
			}

			if DocumentsReceived == destination.Count() {
				log.Error("Same amount of documents in destination interface as before. Can happen due to created_at collission during pagination.")
				return
			}

			log.Debug("Documents", "saved", destination.Count())
			DocumentsReceived = destination.Count()

			if len(response.Documents) == 1 {
				log.Debug("only 1 document in response", "response.Documents", len(response.Documents))
				return
			}

		}
	}

	return
}
Exemplo n.º 10
0
// DisconnectPlayer handles removing a player from the game
func (s *Server) DisconnectPlayer(slot int) {
	log15.Info("Player disconnected", "address", s.ConnectedPlayers[slot].Socket.RemoteAddr(), "slot", slot)

	s.NumConnectedPlayers--
	delete(s.ConnectedPlayers, slot)
}
Exemplo n.º 11
0
// Shutdown is called when the server should prepare for program termination
func (s *Server) Shutdown() {
	log15.Info("Server shutting down!")
	// add shutdown sequence here
}