-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTcpSocketServer.cpp
55 lines (41 loc) · 1.28 KB
/
TcpSocketServer.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
#include "TcpSocketServer.h"
static Thread thread(osPriorityNormal, 1024);
TcpSocketServer::TcpSocketServer(int port): SocketServer(port) {
memset(buffer, 0, (sizeof buffer / sizeof buffer[0]));
}
osStatus TcpSocketServer::run() {
osStatus result = thread.start(callback(this, &TcpSocketServer::loop));
return result;
}
void TcpSocketServer::loop() {
TCPSocket listener;
TCPSocket* client;
bool running = true;
listener.open(net);
nsapi_error_t error = listener.bind(_port);
if (error != NSAPI_ERROR_OK) {
NDBG("error %d \r\n", error);
}
error = listener.listen(this->setting.backlog);
if (error != NSAPI_ERROR_OK) {
NDBG("error %d \r\n", error);
running = false;
} else {
NDBG("Listening on port %d \r\n", _port);
}
client = listener.accept(NULL);
client->set_timeout(this->setting.timeout);
while (running) {
nsapi_size_or_error_t size = client->recv(buffer, sizeof(buffer));
if (size > 0) {
buffer[size] = '\0';
_mycb.call(size); // callback
}
if (size == 0) {
client->close();
client = listener.accept(NULL);
client->set_timeout(this->setting.timeout);
}
}
listener.close();
}