-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
95 lines (71 loc) · 2.57 KB
/
server.cpp
File metadata and controls
95 lines (71 loc) · 2.57 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
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <thread>
#include <cstring>
const int CLIENT_LIMIT = 100;
const size_t MAX_BUFFER_SIZE = 4096;
void server_sender(int client_socket){
char read_buffer[MAX_BUFFER_SIZE];
char write_buffer[MAX_BUFFER_SIZE];
while(1){
size_t bytes_received = read(client_socket, read_buffer, 1024);
std::string client_message(read_buffer,bytes_received);
if (client_message == "end"){
std::cout<<"Connection Closed by Client";
break;
}
std::cout<<"Client Response: "<<client_message<<std::endl;
std::cout<<"Send message to your client: \n";
std::cin.getline(write_buffer, sizeof(write_buffer));
size_t bytes_to_send = strlen(write_buffer);
ssize_t sent_bytes = send(client_socket, write_buffer, bytes_to_send,0);
if (sent_bytes<0){
perror("Sending Message failed, closing connection with client");
close(client_socket);
}
}
close(client_socket);
}
int main(){
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket < 0){
perror("socket failed");
return -1;
}
sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(1100);
if (inet_pton(AF_INET, "0.0.0.0", &server_address.sin_addr) <=0 ){
perror("Failed to convert the given address to a usable binary format");
close(server_socket);
return 0;
}
size_t server_address_size = sizeof(server_address);
//Bind the Socket to the given port
if (bind(server_socket, reinterpret_cast<const sockaddr*>(&server_address), server_address_size) < 0){
perror("Failed to bind the given IP and Port to the server socket");
close(server_socket);
return 0;
}
if (listen(server_socket,CLIENT_LIMIT) < 0){
perror("Failed to listen from the server socket");
close(server_socket);
return 0;
}
std::cout<<"Server Started Listening to Incoming Connections in 0.0.0.0::1100 \n";
while(true){
int client_socket = accept(server_socket, nullptr, nullptr);
if (client_socket<0){
if (client_socket < 0) {
perror("Failed to accept connection\n");
continue;
}else{
std::cout<< "Connected to a Client! \n";
}
}
std::thread client_thread(server_worker, client_socket);
client_thread.detach();
}
}