-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySerialServer.cpp
More file actions
92 lines (75 loc) · 2.56 KB
/
MySerialServer.cpp
File metadata and controls
92 lines (75 loc) · 2.56 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
//
// Created by duni on 12/01/2020.
//
#include "MySerialServer.h"
#include <netinet/in.h>
#include <unistd.h>
#include <iostream>
#include <thread>
#include <algorithm>
// This is a constructor function
MySerialServer::MySerialServer() {
this->run = true;
}
// This function stops the connection
void MySerialServer::stop() {
this->run = false;
}
// This function handles the clients
void acceptClients(bool *run, ClientHandler *ch, int serverFd, sockaddr_in *socketAddress) {
int newSocket;
int addressLength = sizeof(socketAddress);
struct timeval time{};
int timeout_in_seconds = 120;
time.tv_sec = timeout_in_seconds;
// while the function that stops the connection hasn't been called, continue handling the clients
while (run) {
// Accept clients
cout << "accepting clients" << endl;
if (setsockopt(serverFd, SOL_SOCKET, SO_RCVTIMEO, (const char *) &time, sizeof(time))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
if ((newSocket = accept(serverFd, (struct sockaddr *) &socketAddress, (socklen_t *) &addressLength)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
cout << "client connected, listen for messages" << endl;
// Send each client to it's way that calculates the answer to send
ch->handleClient(newSocket);
close(newSocket);
}
close(serverFd);
}
// This function opens the socket and prepares to accept and handle the different clients
void MySerialServer::open(int port, ClientHandler *ch) {
int serverFd, newSocket, readValue;
struct sockaddr_in socketAddress;
int optionNumber = 1;
int addressLength = sizeof(socketAddress);
char *message;
// Create socket
if ((serverFd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Attaching socket
if (setsockopt(serverFd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &optionNumber, sizeof(optionNumber))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
socketAddress.sin_family = AF_INET;
socketAddress.sin_addr.s_addr = INADDR_ANY;
socketAddress.sin_port = htons(port);
if (bind(serverFd, (struct sockaddr *) &socketAddress, sizeof(socketAddress)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(serverFd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// Open the thread
thread threadServer(acceptClients, &run, ch, serverFd, &socketAddress);
threadServer.join();
}