-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.h
More file actions
88 lines (68 loc) · 2.12 KB
/
server.h
File metadata and controls
88 lines (68 loc) · 2.12 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
#ifndef SERVERSOCKET
#define SERVERSOCKET
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <string>
#include <sstream>
#include <chrono>
#include <thread>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstring>
#include <memory>
#include <ws2tcpip.h>
#include <WinSock2.h>
#define MAX_CLIENT_BUFFER_SIZE 1024
class ServerSocket {
private:
std::string host;
unsigned short port;
int socket;
public:
ServerSocket() = delete;
~ServerSocket();
ServerSocket(int socket);
std::string read() const;
void write(const std::string & buf) const;
void close();
};
class Server {
public:
static void connection(const ServerSocket * socket)
{
socket->write("hello from server\n");
std::string s = socket->read();
std::clog << "get from client : " << s << std::endl;
delete socket;
}
Server() = delete;
Server(const std::string & host, unsigned short port)
{
auto wVersionRequested = MAKEWORD(2, 2);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
int listen_socket = ::socket(AF_INET, SOCK_STREAM, 0);
BOOL opt = TRUE;
setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt));
struct sockaddr_in address { 0 };
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(host.c_str());
address.sin_port = htons(port);
int result = bind(listen_socket, (struct sockaddr*)&address, sizeof(address));
if (result == SOCKET_ERROR)
throw std::runtime_error("bind failed");
if (listen(listen_socket, SOMAXCONN) == SOCKET_ERROR)
throw std::runtime_error("listen failed");
while (true) {
int socket = accept(listen_socket, NULL, NULL);
ServerSocket * sock = new ServerSocket(socket);
std::thread th(connection, sock);
th.detach();
}
printf("socket failed with error: %ld\n", WSAGetLastError());
return;
}
~Server() { close(); }
void close() { WSACleanup(); }
};
#endif // SERVERSOCKET