Exemplo n.º 1
0
func listenForMoveRequests(conn *net.TCPConn) {
	listenServe := make(chan []uint8)
	easynet.TieConnToChannel(conn, listenServe)
	for data := range listenServe {
		r := new(ttypes.BotMoveRequest)
		err := json.Unmarshal(data, r)
		easynet.DieIfError(err, "JSON error")

		if r.Kill {
			fmt.Printf("Bot on %s received kill signal\n", os.Args[0])
			os.Exit(0)
		}

		fmt.Printf("Bot at %d, %d received messages: %v\n", r.YourX, r.YourY, r.Messages)
		fmt.Printf("  Sees other bots: %v\n", r.OtherBots)
		//Do something

		response := new(ttypes.BotMoveResponse)
		if r.YourY < 5 {
			response.MoveDirection = "up"
		} else if r.YourY > 5 {
			response.MoveDirection = "down"
		}
		// response.BroadcastMessage = fmt.Sprintf("'I am %v at %d, %d'", os.Args[0], r.YourX, r.YourY)
		responseString, err := json.Marshal(response)
		easynet.DieIfError(err, "JSON marshal error")
		conn.Write(responseString)
	}
}
Exemplo n.º 2
0
// Set up incoming and outgoing TCP connections to all adjacent coordinators
func connectToAdjacents(listener *net.TCPListener) chan bool {
	adjsServe = make(CoordMap, len(config.AdjacentCoords))
	adjsRequest = make(CoordMap, len(config.AdjacentCoords))
	listenServe = make(chan []uint8)

	serveFound := make(chan int)
	requestFound := make(chan int)
	allDone := make(chan bool)

	go func() {
		for _, adj := range config.AdjacentCoords {
			go func() {
				adjsRequest[adj.Identifier] = easynet.Dial(adj.Address)
				adjsRequest[adj.Identifier].Write([]uint8(strconv.Itoa(config.Identifier)))
				requestFound <- adj.Identifier
			}()
			go func() {
				newConn := easynet.Accept(listener)
				identifier, err := strconv.Atoi(string(easynet.ReceiveFrom(newConn)))
				easynet.DieIfError(err, "String conversion error")
				adjsServe[identifier] = newConn
				easynet.TieConnToChannel(newConn, listenServe)
				serveFound <- identifier
			}()
		}

		for i := 0; i < len(config.AdjacentCoords); i++ {
			<-requestFound
			<-serveFound
		}

		fmt.Printf("%d is connected to all neighbors\n", config.Identifier)

		allDone <- true
	}()

	return allDone
}