int client_main(int argc, char *argv[])
{
	if ((argc < 3) || (argc > 4))
	{   // Test for correct number of arguments
		std::cerr << "Usage: " << argv[0]
			<< " <Server> <Echo String> [<Server Port>]\n";
		exit(1);
	}

	std::string servAddress = argv[1];             // First arg: server address
	char* echoString = argv[2];               // Second arg: string to echo
	int echoStringLen = strlen(echoString);   // Length of string to echo
	if (echoStringLen > ECHOMAX)
	{    // Check input length
		std::cerr << "Echo string too long" << std::endl;
		exit(1);
	}
	unsigned short echoServPort = Socket::ResolveService(
		(argc == 4) ? argv[3] : "echo", "udp");

	try
	{
		UDPSocket sock;

		// Send the string to the server
		sock.SendTo(echoString, echoStringLen, servAddress, echoServPort);

		// Receive a response
		char echoBuffer[ECHOMAX + 1];       // Buffer for echoed string + \0
		int respStringLen;                  // Length of received response
		if ((respStringLen = sock.Receive(echoBuffer, ECHOMAX)) != echoStringLen)
		{
			std::cerr << "Unable to receive" << std::endl;
			exit(1);
		}

		echoBuffer[respStringLen] = '\0';             // Terminate the string!
		std::cout << "Received: " << echoBuffer << std::endl;   // Print the echoed arg

													  // Destructor closes the socket

	}
	catch (SocketException &e)
	{
		std::cerr << e.what() << std::endl;
		exit(1);
	}

	return 0;
}
Beispiel #2
0
	void Run()
	{
		const int port = 30003;
		UDPSocket socket;
		socket.Bind(port);

		const char sendbuffer[] = "hello world!";
		socket.Send(Address(127,0,0,1,port), sendbuffer, sizeof(sendbuffer));

		sleep_ms(50);

		char rcvbuffer[256];
		memset(rcvbuffer, 0, sizeof(rcvbuffer));
		Address sender;
		for(;;)
		{
			int bytes_read = socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer));
			if(bytes_read < 0)
				break;
		}
		//FIXME: This fails on some systems
		assert(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0);
		assert(sender.getAddress() == Address(127,0,0,1, 0).getAddress());
	}