-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.cpp
53 lines (41 loc) · 1.14 KB
/
common.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
#include "common.h"
#include <bits/stdc++.h>
#include <sys/socket.h>
#include <sys/types.h>
using namespace std;
int recv_all(int sockfd, void *buffer, size_t len) {
size_t bytes_received = 0;
size_t bytes_remaining = len;
char *buff = (char *)buffer;
while (bytes_remaining > 0) {
size_t result = recv(sockfd, buff + bytes_received, bytes_remaining, 0);
if (result == 0)
break; // Connection closed
else if (result < 0)
return -1; // Error
bytes_received += result;
bytes_remaining -= result;
}
return bytes_received;
}
int send_all(int sockfd, void *buffer, size_t len) {
size_t bytes_sent = 0;
size_t bytes_remaining = len;
char *buff = (char *)buffer;
while (bytes_remaining > 0) {
ssize_t result = send(sockfd, buff + bytes_sent, bytes_remaining, 0);
if (result < 0) return -1; // Error
bytes_sent += result;
bytes_remaining -= result;
}
return bytes_sent;
}
vector<string> parse_cmd(char *buf) {
vector<string> tokens = {};
char *token = strtok(buf, " \n");
while (token != NULL) {
tokens.push_back(token);
token = strtok(NULL, " \n");
}
return tokens;
}