81 lines
2.0 KiB
C++
81 lines
2.0 KiB
C++
|
#include "Network.hpp"
|
||
|
#include <cstring>
|
||
|
#include <stdio.h>
|
||
|
#include <iostream>
|
||
|
#include <unistd.h>
|
||
|
#include <algorithm>
|
||
|
|
||
|
Network::Network(){
|
||
|
conf = new Config("config.txt");
|
||
|
memset(&server, 0, sizeof(server));
|
||
|
server.sin_family = AF_INET;
|
||
|
server.sin_port = htons(stoi(conf->getValue("port")));
|
||
|
inet_aton(conf->getValue("ip").c_str(), &server.sin_addr);
|
||
|
/* server.sin_addr.s_addr = INADDR_ANY; */
|
||
|
|
||
|
main_socket = socket(server.sin_family, SOCK_STREAM, 0);
|
||
|
if(main_socket == -1){
|
||
|
perror("Socket");
|
||
|
}
|
||
|
|
||
|
if(bind(main_socket, (sockaddr*)&server, sizeof(server))){
|
||
|
perror("Bind");
|
||
|
}
|
||
|
|
||
|
if(listen(main_socket, 5) == -1){
|
||
|
perror("Listeen");
|
||
|
}
|
||
|
}
|
||
|
void Network::run(){
|
||
|
|
||
|
accepted_sock.resize(stoi(conf->getValue("conn_limit")));
|
||
|
/* motd = conf->getValue("motd").c_str(); */
|
||
|
/* std::cout << motd << std::endl; */
|
||
|
|
||
|
while(!will_close){
|
||
|
FD_ZERO(&readfds);
|
||
|
FD_SET(main_socket, &readfds);
|
||
|
max_fd = main_socket;
|
||
|
|
||
|
//construct fd_set and get max fd
|
||
|
for(int fd: accepted_sock){
|
||
|
if(fd > 0){
|
||
|
FD_SET(fd, &readfds);
|
||
|
if(max_fd < fd){ max_fd = fd; }
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if(select(max_fd+1, &readfds, NULL, NULL, NULL) < 0){
|
||
|
perror("select");
|
||
|
}
|
||
|
|
||
|
if(FD_ISSET(main_socket, &readfds)){
|
||
|
int _incomming_socket = accept(main_socket, (struct sockaddr*)&new_sockaddr, &sin_size);
|
||
|
if(_incomming_socket == -1){
|
||
|
perror("accept");
|
||
|
}
|
||
|
accepted_sock.push_back(_incomming_socket);
|
||
|
std::cout << "New Connection: " << inet_ntoa(new_sockaddr.sin_addr) << std::endl;
|
||
|
/* if(send(_incomming_socket, &motd, sizeof(&motd), 0) == -1){perror("sendt");} */
|
||
|
}else{
|
||
|
for(int fd: accepted_sock){
|
||
|
if(FD_ISSET(fd, &readfds)){
|
||
|
if((rcv_bytes = recv(fd, &msg, sizeof(msg),0)) == 0){
|
||
|
std::cout << "disconnected" << std::endl;
|
||
|
close(fd);
|
||
|
accepted_sock.erase(std::find(accepted_sock.begin(), accepted_sock.end(), fd));
|
||
|
}else{
|
||
|
msg[rcv_bytes] = '\0';
|
||
|
std::cout << "he sent :" << msg << std::endl;
|
||
|
if(std::strcmp(msg, "ping")){
|
||
|
send(fd, "pong", 4, 0);
|
||
|
}
|
||
|
}
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|
||
|
}
|
||
|
}
|