-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
103 lines (80 loc) · 2.01 KB
/
server.cpp
File metadata and controls
103 lines (80 loc) · 2.01 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
97
98
99
100
101
102
#include "server.h"
server::server()
{
}
server::~server()
{
}
bool server::init(std::string ip, int port)
{
#ifndef __linux
WSADATA wsa;
//Initialise winsock
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return false;
}
printf("Initialised.\n");
#endif
//Create socket
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
serv.sin_family = AF_INET;
const char* tempclient_ip = ip.c_str();
serv.sin_addr.s_addr = inet_addr(tempclient_ip);
serv.sin_port = htons(port);
//Bind
if (bind(socket_desc, (struct sockaddr *)&serv, sizeof(serv)) < 0)
{
//print the error message
perror("bind failed. Error");
return false;
}
puts("bind done");
//Listen
listen(socket_desc, 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return false;
}
puts("Connection accepted");
return true;
}
void server::sendVector(std::vector<char> * buffer)
{
memcpy(bufferSend, &(*buffer)[0], buffer->size());
if (send(client_sock, bufferSend, buffer->size(), 0) < 0)
{
printf("Send failed\n");
}
#ifdef debugServer
printf("server send\n");
#endif
}
std::vector<char>* server::recvVector(std::vector<char> * buffer)
{
int read_size = 0;
while ((read_size = recv(client_sock, bufferRecv, MAX_BUFFER, 0)) < 0)
{
}
//deep copy
buffer->clear();
for (int x = 0; x < read_size; x++)
{
buffer->push_back(bufferRecv[x]);
}
return buffer;
}