Repository navigation
Expand file tree
/
Copy pathSocket.cpp
More file actions
96 lines (76 loc) · 1.78 KB
/
Copy pathSocket.cpp
File metadata and controls
96 lines (76 loc) · 1.78 KB
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
92
93
94
95
96
#include "Socket.hpp"
#include <sys/socket.h>
#include <iostream>
#include <vector>
#include <cstdint>
#include <unistd.h>
using namespace std;
using HeaderType = int32_t;
Socket::Socket():
m_fd(0),
m_isAlive(false)
{
}
Socket::Socket(int fd):
m_fd(fd),
m_isAlive(true)
{
}
Socket::~Socket()
{
cout << "Destroying socket" << endl;
close(m_fd);
}
/*
int Socket::fd() const
{
return m_fd;
}
*/
bool Socket::isAlive() const
{
return m_isAlive;
}
void Socket::sendString(const string& message)
{
// Sending header
HeaderType messageLength = message.size();
//if(send(m_fd, &messageLength, sizeof(HeaderType), 0) < sizeof(HeaderType)){
if(send(m_fd, &messageLength, sizeof(HeaderType), MSG_NOSIGNAL) < sizeof(HeaderType)){
kill();
return;
}
// Sending data
//if(send(m_fd, message.c_str(), messageLength, 0) < messageLength){
if(send(m_fd, message.c_str(), messageLength, MSG_NOSIGNAL) < messageLength){
kill();
}
}
string Socket::receiveString()
{
string message = "";
// Get header
HeaderType messageLength = 0;
if(recv(m_fd, &messageLength, sizeof(HeaderType), 0) > 0 && messageLength <= MAXPACKETSIZE){
vector<char> buffer;
buffer.resize(messageLength);
// Get data
HeaderType receivedBytes = 0;
HeaderType newQuantity = 0;
do{
newQuantity = recv(m_fd, &buffer[0], messageLength - receivedBytes, 0);
receivedBytes += newQuantity;
}
while(receivedBytes < messageLength && receivedBytes > 0 && newQuantity > 0);
message = string(buffer.begin(), buffer.end());
}
else{
kill();
}
return message;
}
void Socket::kill()
{
cout << "Killing client" << endl;
m_isAlive = false;
}