#include <iostream>
#include <fstream>
#include <thread>
#include <cstdlib>
#include <cstdint>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
class Client {
public:
Client(string name_c , int socket ,int id):name(name_c) , id(id) , sock_c(socket){}
Client();
int sock_c;
int get_id(){
return id;
}
private:
int id;
string name;
};
int client_all = 1;
Client arr_all[numeric_limits<int>::max()];
enum chat_func {
reg = '0',
write_read = '1'
};
struct config_server {
string ip;
int port;
int protocol_inet;
int protocol;
struct sockaddr_in addr;
};
void up_server(int &sock , int &listener , config_server &conf){
listener = socket(conf.protocol_inet, conf.protocol, 0);
conf.addr.sin_family = conf.protocol_inet;
conf.addr.sin_port = htons(conf.port);
conf.addr.sin_addr.s_addr = inet_addr(conf.ip.c_str());
bind(listener, (struct sockaddr*)&conf.addr, sizeof(conf.addr));
listen(listener, 1);
}
void thread_func_rw(char *str_in_chat){ //primer zaprosa 1:andrei:12.57:LOL kek bubu gaga
string str = str_in_chat;
str.erase(0 , 1);//andrei:12.57:LOL kek bubu gaga
for(int i = 0; i < client_all; i++){
send(arr_all[i].sock_c , str.c_str() , strlen(str.c_str()) , 0);
}
this_thread::yield();
}
void thread_func_reg(char *new_client_in_chat , int sock_client){ //primer zaprosa : 0:andrei
string new_client = new_client_in_chat;
new_client.erase(0 , 1);
Client buf(new_client , sock_client , client_all + 1);
arr_all[client_all - 1] = buf;
send(sock_client , "100" , 3 , 0);
this_thread::yield();
}
int main(int argc, char const *argv[]) {
cout << "start config Server Poti" << endl;
config_server conf_serv;
conf_serv.ip = "127.0.0.1";conf_serv.port = 8080;conf_serv.protocol = SOCK_STREAM;conf_serv.protocol_inet = AF_INET;
int sock , listener;
char str_zapros[2048];
up_server(sock , listener , conf_serv);
cout << "Server up" << endl;
thread thr_rw_in_chat(thread_func_rw , str_zapros);
thread thr_reg(thread_func_reg , str_zapros , sock);
while(true){
sock = accept(listener, NULL, NULL);
recv(sock , str_zapros , 2048 , 0);
cout << "Server do new zapros" << endl;
if (write_read == str_zapros[0]){
thr_rw_in_chat.detach();
}
else if (reg == str_zapros[0]) {
thr_reg.detach();
}
//close(sock);
}
}