Exemplo n.º 1
0
/**
HANDLES REQUEST
*/
func (t *TcpMessageHub) handleRequest(id uint64) error {

	for {

		// Read request
		request, err := utils.Read(t.conns[id])

		if err != nil {
			if err == io.EOF {
				break
			}
			fmt.Println("Error reading request:", err.Error())
			return err
		}

		fmt.Println("Request from client:", string(request))

		// Decode request
		decoded, err := messages.Decode(request)

		if err != nil {
			fmt.Println("Error decoding request:", err.Error())
			return err
		}

		// Handle request and build response
		var response messages.Response
		switch decoded.GetMessageType() {
		case messages.EchoRequestMessage:
			response = services.HandleEcho(decoded.(messages.EchoRequest), id)
		case messages.IdRequestMessage:
			response = services.HandleId(decoded.(messages.IdRequest), id)
		case messages.ListRequestMessage:
			response = services.HandleList(decoded.(messages.ListRequest), id, t.ClientIDs())
		case messages.RelayRequestMessage:
			response = services.HandleRelay(decoded.(messages.RelayRequest))
		default:
			err := errors.New("Error handling: Cannot find handler for this message type")
			return err
		}

		t.handleResponse(response)

	}

	return nil
}
/**
WAIT FOR RESPONSE
*/
func (t *TcpMessageClient) WaitForResponse() (messages.Response, error) {

	// Get response
	response, err := utils.Read(t.conn)

	fmt.Println("Response from hub:", string(response))

	if err != nil {
		fmt.Println("Error reading response:", err.Error())
		return nil, err
	}

	// Decode response
	decoded, err := messages.Decode(response)

	if err != nil {
		fmt.Println("Error decoding response:", err.Error())
		return nil, err
	}

	return decoded.(messages.Response), nil
}