Akatas_Kingdom/server/Network.cpp

83 lines
2.0 KiB
C++
Raw Normal View History

#include "Network.hpp"
#include <cstring>
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <algorithm>
Network::Network(){
conf = new Config("config.txt");
2021-12-16 00:11:41 +01:00
strcpy(motd, conf->getValue("motd").c_str());
strcat(motd, "\n");
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);
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")));
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;
2021-12-16 00:11:41 +01:00
if(send(_incomming_socket, motd, strlen(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{
2021-12-16 00:11:41 +01:00
std::cout << "he sent :" << rcv_bytes << " bytes and it says: " << msg;
if(std::strncmp("ping", msg, rcv_bytes-1) == 0){
send(fd, "pong", 5, 0);
}
2021-12-16 00:11:41 +01:00
}
break;
}
}
}
}
}