summaryrefslogtreecommitdiffstats
path: root/test/src/test-sockets.cpp
blob: a712da06381cf8ac79c96fe1a2e7497304f1f9fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "uscxml/config.h"
#include "uscxml/server/Socket.h"
#include <iostream>

#include <event2/event.h>
#include "event2/thread.h"

#ifdef HAS_SIGNAL_H
#include <signal.h>
#endif

#include "uscxml/concurrency/tinythread.h"

using namespace uscxml;

class TestServer : public ServerSocket {
public:
	TestServer(int domain, int type, int protocol) : ServerSocket(domain, type, protocol) {}
	virtual void readCallback(const char* data, size_t size, Connection& conn) {
		std::string content(data, size);
//		std::cout << "Server got: " << content << std::endl;
		std::string urghs("hi!");
		conn.reply(urghs.data(), urghs.size());
	};
};

class TestClient : public ClientSocket {
public:
	TestClient(int domain, int type, int protocol) : ClientSocket(domain, type, protocol) {}
	virtual void readCallback(const char* data, size_t size) {
		std::string content(data, size);
	};
};

int main(int argc, char** argv) {

#if defined(HAS_SIGNAL_H) && !defined(WIN32)
	signal(SIGPIPE, SIG_IGN);
#endif

#ifndef _WIN32
	evthread_use_pthreads();
#else
	evthread_use_windows_threads();
#endif

	if (0) {
		// start server socket and connect
		int iterations = 100;

		TestServer server(PF_INET, SOCK_STREAM, 0);
		try {
			server.listen("*", 1234);

			while(iterations--) {
				std::cout << iterations << std::endl;
				TestClient client(PF_INET, SOCK_STREAM, 0);
				client.connect("127.0.0.1", 1234);

				std::string hello("hello");
				client.write(hello.data(), hello.size());

				tthread::this_thread::sleep_for(tthread::chrono::milliseconds(20));
			}

		} catch (std::runtime_error e) {
			std::cout << e.what() << std::endl;
		}
	}

	{
		// connect client to server and kill server
		int iterations = 100;

		try {

			while(iterations--) {
				std::cout << iterations << std::endl;
				TestServer* server = new TestServer(PF_INET, SOCK_STREAM, 0);
				server->listen("*", 1236 + iterations);

				TestClient client(PF_INET, SOCK_STREAM, 0);
				client.connect("127.0.0.1", 1236 + iterations);

				std::string hello("hello");
				client.write(hello.data(), hello.size());

				delete server;

				tthread::this_thread::sleep_for(tthread::chrono::milliseconds(20));
			}

		} catch (std::runtime_error e) {
			std::cout << e.what() << std::endl;
		}

	}
}