forked from GeorgeArgyros/mt_derand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.cpp
91 lines (72 loc) · 1.37 KB
/
server.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "server.hpp"
int
SimpleServer::setup( unsigned short int port, std::string ipaddr)
{
idle = true;
if ((lsock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1;
memset(&addr, '\0', sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ipaddr.c_str());
int yes = 1;
if ( setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1 )
return -1;
if (bind(lsock, (struct sockaddr *) &addr, sizeof(addr)) < 0)
return -1;
return 0;
}
int
SimpleServer::waitForClient()
{
socklen_t len;
if (listen(lsock, 10) < 0)
return -1;
if ((csock = accept(lsock, (struct sockaddr *)&caddr, &len)) < 0)
return -1;
idle = false;
return 0;
}
ssize_t
SimpleServer::crecv(void *buffer, size_t len)
{
ssize_t ret;
ret = recv(csock, buffer, len, 0);
if (ret == 0){
close(csock);
idle = true;
}
return ret;
}
ssize_t
SimpleServer::csend(const void *buffer, size_t len)
{
return send(csock, buffer, len, 0);
}
void
SimpleServer::shutdown()
{
close(csock);
close(lsock);
}
bool
SimpleServer::isIdle()
{
return idle;
}
/*
int main()
{
SimpleServer ss;
char buf[100];
ss.setup();
while (1) {
ss.waitForClient();
ss.csend("lalala", sizeof("lalala"));
ss.crecv((void *)buf, sizeof(buf));
if (buf[1] == 'a')
break;
}
return 0;
}
*/