Blob Blame Raw

#include <cstring>

#include "tcp.h"
#include "main.h"


int main(int argc, char** argv) {
	if (argc != 2)
		{ printf("one arg expected\n"); return 1; }
	
	Tcp::Address address(127, 0, 0, 1, 1562);
	
	if (0 == strcmp(argv[1], "tcpconnect")) {
		printf("tcpconnect\n");
		
		Tcp::Connection connection;
		if (connection.open(address))
			printf( "connected to server: %hhd.%hhd.%hhd.%hhd:%hd\n",
					address.ip[0], address.ip[1], address.ip[2], address.ip[3], address.port );
		char buf[65] = {};
		while(connection.check()) {
			sprintf(buf, "client say %d\n", rand());
			if (connection.write(buf, sizeof(buf) - 1))
				printf("sent: %s\n", buf);
			if (connection.read(buf, sizeof(buf) - 1))
				printf("received: %s\n", buf);
		}
		
		printf("last error: %u\n", connection.getLastError());
		return connection.getLastError();
	}
	
	if (0 == strcmp(argv[1], "tcpserver")) {
		printf("tcpserver\n");
		
		class Handler: public Tcp::Handler {
		public:
			void handleTcpConnection(Tcp::Connection &connection) override {
				const Tcp::Address &address = connection.getRemoteAddr();
				printf( "received connection from: %hhd.%hhd.%hhd.%hhd:%hd\n",
						address.ip[0], address.ip[1], address.ip[2], address.ip[3], address.port );
				while(connection.check()) {
					char buf[65] = {};
					if (connection.read(buf, sizeof(buf) - 1))
						printf("received: %s\n", buf);
					sprintf(buf, "server say %d\n", rand());
					if (connection.write(buf, sizeof(buf) - 1))
						printf("sent: %s\n", buf);
				}
			}
		} handler;
		
		Tcp::Server server;
		if (server.start(address, &handler))
			printf( "listening at: %hhd.%hhd.%hhd.%hhd:%hd\n",
					address.ip[0], address.ip[1], address.ip[2], address.ip[3], address.port );
		server.join();
		
		printf("last error: %u\n", server.getLastError());
		return server.getLastError();
	}

	printf("wrong args\n");
	return 1;
}