forked from Andersbakken/rct
-
Notifications
You must be signed in to change notification settings - Fork 2
/
SocketTestSuite.cpp
75 lines (55 loc) · 1.95 KB
/
SocketTestSuite.cpp
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
#include "SocketTestSuite.h"
#include "DeferredAssert.h"
#include <rct/EventLoop.h>
#include <rct/SocketServer.h>
#include <rct/Log.h>
#include <thread>
void SocketTestSuite::unixSockets()
{
const Path unixPathToUse("test_unixSocket");
// need to delete the file if it already exists
unixPathToUse.rm();
// We need an event loop to receive signals.
EventLoop::SharedPtr loop(new EventLoop);
loop->init(EventLoop::MainEventLoop);
// create the server
SocketServer::SharedPtr s(new SocketServer);
// This will hold the client connection that the server gets once a client
// connects.
SocketClient::SharedPtr serverConnection;
s->newConnection().connect([&](SocketServer *s)
{
// important: serverConnection needs to survive beyond this lambda,
// otherwise the connection will be closed on scope exit.
serverConnection = s->nextConnection();
// by this point, the client will already have gotten the HUP (hang
// up), so they don't receive the message :(
serverConnection->write("msg frm server");
});
CPPUNIT_ASSERT(s->listen(unixPathToUse));
std::thread serverThread([&](){loop->exec(300);});
realSleep(100);
SocketClient::SharedPtr client(new SocketClient(SocketClient::Unix));
int numReadsFromClient = 0;
client->readyRead().connect([&](SocketClient::SharedPtr, Buffer &&b)
{
std::string receivedData(b.data(), b.end());
debug() << "client received " << receivedData;
numReadsFromClient++;
});
CPPUNIT_ASSERT(client->connect(unixPathToUse));
realSleep(100);
serverThread.join();
CPPUNIT_ASSERT(numReadsFromClient == 1);
}
void SocketTestSuite::realSleep(int ms)
{
#ifdef _WIN32
Sleep(ms);
#else
timespec s;
s.tv_sec = ms/1000;
s.tv_nsec = (ms%1000) * 1000 * 1000;
while(nanosleep(&s, &s) == -1 && errno == EINTR);
#endif
}