-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cc
107 lines (76 loc) · 2.52 KB
/
Server.cc
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
103
104
105
106
107
#include "Server.h"
#include <iostream>
#include "ClientInterface.h"
#include "ServerApplication.h"
using namespace std;
using namespace TP1;
const unsigned MAX_NUM_CONNECTIONS = 7;
const unsigned MAX_BUF = 101;
void Server::setUp(string port) {
//helper variable to check for errors
int returnCode = -1;
if (LOGGING) {
cout << "Binding server..." << endl;
}
_serverSocketId = socket(AF_INET6, SOCK_STREAM, 0);
if (_serverSocketId < 0) {
cout << "ERROR setting up socket" << endl;
exit(1);
}
//Initializing socket structure
//in6addr_any allows connection from both ipv6 and ipv4
bzero(&_serverSocket, sizeof(_serverSocket));
_serverSocket.sin6_family = AF_INET6;
_serverSocket.sin6_port = htons(stoi(port));
_serverSocket.sin6_addr = in6addr_any;
_addrLen = sizeof(_clientSocketId);
returnCode = bind(_serverSocketId, (sockaddr*) &_serverSocket, sizeof(_serverSocket));
if (returnCode < 0 ) {
cout << "ERROR binding server socket." << endl;
cout << "Maybe try a different port?" << endl;
exit(1);
}
//Listens to MAX_NUM_CONNECTIONS at most
listen(_serverSocketId, MAX_NUM_CONNECTIONS );
}
void Server::closeConnection(int clientId) {
if (LOGGING) {
cout << "Closing connection to client..." << endl;
}
//TODO - remove client from _clientList (in the future)
sendMessageToClient(clientId, "-1");
close(clientId);
if (LOGGING) {
cout << "Client is out" << endl;
}
}
int Server::acceptClient() {
if (LOGGING) {
cout << "Waiting for client" << endl;
}
_clientSocketId = accept(_serverSocketId, (sockaddr*) &_clientSocketId, &_addrLen );
//TODO - Implement and return the Client object in the near future
//For now, the server only takes one client at a time, so no need
//for it. An int will suffice
if (LOGGING) {
cout << "Client accepted..." << endl;
}
return _clientSocketId;
}
string Server::getMessageFromClient(int clientId) {
if (LOGGING) {
cout << "Waiting for client message" << endl;
}
char msg[MAX_BUF];
recv(clientId,msg,MAX_BUF, 0);
if (LOGGING) {
cout << "Got client message: " << msg << endl;
}
return string(msg);
}
void Server::sendMessageToClient(int clientId, string message) {
if (LOGGING) {
cout << "Sending message to client: " << message << "." << endl;
}
send(clientId, message.c_str(), message.size()+1, 0);
}