-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
99 lines (80 loc) · 2.8 KB
/
main.cpp
File metadata and controls
99 lines (80 loc) · 2.8 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
/*
* File: main.cpp
* Author: Mike Curry
* License: The MIT License (MIT)
*
* Created on February 27, 2015, 12:48 PM
*/
#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include "Logger.h"
#include "sockets.h"
#define PORT "8080" // the port users will be connecting to
#define BACKLOG 256 // how many pending connections queue will hold
using namespace std;
int main() {
int serverSocket, clientSocket; // listen on sock_fd, new connection on new_fd
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
char s[INET6_ADDRSTRLEN];
int status = createserver(BACKLOG, PORT, serverSocket);
if (status < 0) {
cerr << "Couldn't create the server.." << endl;
exit(1);
}
while (true) {
// wait for a connection
sin_size = sizeof their_addr;
clientSocket = accept(serverSocket, reinterpret_cast<sockaddr *>(&their_addr), &sin_size);
if (clientSocket == -1) {
cerr << "client accept error" << endl;
continue;
}
// get the ip of the new connection
inet_ntop(their_addr.ss_family, get_in_addr(reinterpret_cast<sockaddr *>(&their_addr)), s, sizeof s);
cout << "server: got connection from " << s << endl;
// fork off
if (!fork()) {
// this is now the child process, close the server socket as its no longer required
close(serverSocket);
int status;
int timeouts = 0;
while (true) {
// send some response...
string message = "Here is the data you sent: ";
string receiveBuffer;
// get some data
status = receive(clientSocket, receiveBuffer);
if (status == 0) {
// disconnected?
timeouts = 0;
break;
} else if (status == -1) {
// error
timeouts = 0;
break;
} else if (status == -2) {
++timeouts;
if (timeouts > 10) {
break;
}
} else {
// process the data we just received!
string sBuffer = message + receiveBuffer;
timeouts = 0;
status = send(clientSocket, sBuffer);
if (status == -1) {
cerr << "There was an error!" << endl;
break;
}
}
}
// kill the connection off & exit
close(clientSocket);
exit(0);
}
close(clientSocket); // parent doesn't need this
}
return 0;
}