-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.cpp
50 lines (41 loc) · 1.19 KB
/
net.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
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "types.h"
void error (const char *msg) {
perror(msg);
exit(1);
}
// Move me!
bool operator == (const player_matchmaking_t& a, const player_matchmaking_t& b) {
return strcmp(a.name, b.name) == 0;
}
/* Receive len amount of byte completely (no partial recv) */
int recv_complete (int sockfd, void *buf, size_t len, int flags) {
int bytesRead = 0;
int result;
while (bytesRead < len) {
result = recv (sockfd, (char*)buf + bytesRead, len - bytesRead, flags);
if (result < 1) {
return -1;
}
bytesRead += result;
}
return bytesRead;
}
/* Start server. By default port = 4545 */
int server (int port) {
struct sockaddr_in serv_addr;
int sock = socket(AF_INET, SOCK_STREAM, 0);;
if (sock < 0)
error("ERROR opening socket");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
if (bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sock, 5);
return sock;
}