我在一个小型 tcp 聊天服务器上写作,但我遇到了一些我无法弄清楚如何“优雅”解决的问题。
下面是我的主循环的代码:它确实:
1. 当建立新的 tcp 连接时,使用标记的基本事件启动一个向量。
2. 获取此连接并将其推回向量中。然后使用套接字创建一个 CSingleConnection 对象并将套接字传递给它。
2.1。从 CSingleConnection 获取事件,该事件在连接接收到数据时被标记...
3. 当它接收到数据时。等待已满并返回数组中句柄的编号...与所有其他向量似乎我可以确定现在正在发送哪个...
但是每个人都可以看到:这种方法真的很差......我无法弄清楚如何更好地完成这一切,获取连接套接字,创建单个连接等等:/...
有什么建议、改进等吗?...
void CServer::MainLoop()
{
DWORD dwResult = 0;
bool bMainLoop = true;
std::vector<std::string> vecData;
std::vector<HANDLE> vecEvents; //Contains the handles to wait on
std::vector<SOCKET> vecSocks; //contains the sockets
enum
{
ACCEPTOR = 0, //First element: sequence is mandatory
EVENTSIZE //Keep as the last element!
};
//initiate the vector with the basic handles
vecEvents.clear();
GetBasicEvents(vecEvents);
while(bMainLoop)
{
//wait for event handle(s)
dwResult = WaitForMultipleObjects(vecEvents.size(), &vecEvents[0], true, INFINITE);
//New connection(s) made
if(dwResult == (int)ACCEPTOR)
{
//Get the sockets for the new connections
m_pAcceptor->GetOutData(vecSocks);
//Create new connections
for(unsigned int i = 0; i < vecSocks.size(); i++)
{
//Add a new connection
CClientConnection Conn(vecSocks[i]);
m_vecConnections.push_back(Conn);
//Add event
vecEvents.push_back(Conn.GetOutEvent());
}
}
//Data from one of the connections
if(dwResult >= (int)EVENTSIZE)
{
Inc::MSG Msg;
//get received string data
m_vecConnections[dwResult].GetOutData(vecData);
//handle the data
for(unsigned int i = 0; i < vecData.size(); i++)
{
//convert data into message
if(Inc::StringToMessage(vecData[i], Msg) != Inc::SOK)
continue;
//Add the socket to the sender information
Msg.Sender.sock = vecSocks[dwResult];
//Evaluate and delegate data and task
EvaluateMessage(Msg);
}
}
}
}