Example #1
0
void messagesLoop()
{
	vector<size_t> messages_ids;
	Message msg;
	Group online;
	string src;
	string dst;
	string net_msg;
	int sock;
	size_t msg_id;

	while(true)
	{
		chat_mtx.lock();	
		messages_ids = chat.getMessagesIds();		
		for(auto const& id: messages_ids)
		{
			online = chat.getGroup(ONLINE_GROUP);
			msg = chat.getMessage(id);
			src = msg.getSrcUserName();
			dst = msg.getDstUserName();
			bool is_file = msg.hasTitle();
			if(online.has(src) && online.has(dst))
			{
				sock = chat.getSocketFromUser(dst);	
				if(is_file)
					net_msg = hostToNetFileIncoming(msg);
				else
					net_msg = hostToNetMsgIncoming(msg);
				//cout << "sock1 = " << sock << endl;
				//sending message to destiny user
				if(send(sock, net_msg) < 0)
				{
					cout << "error sending message from " + src + " to " + dst
						<< ":" << endl;
					perror("");
				}
				else
				{
					msg_id = hash<Message>{}(msg);
					chat.delMessage(msg_id);
					sock = chat.getSocketFromUser(src);	
					//cout << "sock2 = " << sock << endl;
					if(is_file)
						net_msg = hostToNetFileSent(msg_id);
					else
						net_msg = hostToNetMsgSent(msg_id);
					//notificating source user
					if(send(sock, net_msg) < 0)
					{
						cout << "error sending " << (is_file?"file":"message")
							<< " from " << src << " to " << dst << ":" << endl;
						perror("");
					}
				}
			}
		}
		chat_mtx.unlock();	

		this_thread::sleep_for(chrono::milliseconds(MSG_LOOP_TIME_MS));
	}
}