forked from maxtors/Webserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cSocket.cpp
67 lines (54 loc) · 2.51 KB
/
cSocket.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
#include <WinSock2.h>
#include <string>
#include "Webserver.h"
#define CSOCKET_ERROR -1
#define CSOCKET_END 0
#define CSOCKET_VERSION 2
// ---------- cScoket Constructor ---------------------------------------------
cSocket::cSocket(SOCKET s) { sock_ = s; }
// ---------- cScoket Deonstructor --------------------------------------------
cSocket::~cSocket() { close(); }
// ---------- Close the socket ------------------------------------------------
inline void cSocket::close() { closesocket(sock_); }
// ---------- Receive Data ----------------------------------------------------
std::string cSocket::rxData() {
char buffer[1024];
int retval; // Number of bytes received
while (true) {
retval = recv(sock_, buffer, sizeof(buffer)-1, 0);
if (retval == CSOCKET_END) { // If 0 bytes received
break; // Connection was closed
}
else if (retval == CSOCKET_ERROR) { // If error value received
throw "socket error while receiving.";
}
else {
buffer[retval] = 0; // Terminate buffer with \0
return buffer; // Return buffer
}
}
return ""; // Fallback return
}
// ---------- Receive a single line -------------------------------------------
std::string cSocket::rxLine() {
std::string result; // String to hold the received line
char r; // Buffer for receiving char
int rStatus; // Receive status
while (true) { // Loop until line is read
rStatus = recv(sock_, &r, 1, 0); // Receive a char
if (rStatus == CSOCKET_END) return result;
else if (rStatus == CSOCKET_ERROR) return "";
result += r; // Append to result
if (r == '\n') return result; // If newline, return result
}
return result; // Fallback return
}
// ---------- Transmit data ---------------------------------------------------
void cSocket::txData(char* data, int size) {
send(sock_, data, size, 0); // Send data on socket
}
// ---------- Transmit a single line ------------------------------------------
void cSocket::txLine(std::string line) {
line += "\n"; // Append newline char
send(sock_, line.c_str(), line.length(), 0); // Send line on socket
}