【发布时间】:2017-03-04 14:22:45
【问题描述】:
我正在使用 Visual Studio 2015。
我有主循环,我在其中处理与服务器的新连接:
void Server::acceptorLoop()
{
acceptor = new boost::asio::ip::tcp::acceptor(service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 8001));//boost::asio::ip::address::from_string("xx.xx.xx.xx"), 80)
std::cout << "Waiting for clients..." << std::endl;
while (TRUE)
{
boost::asio::ip::tcp::socket* clientSock = new boost::asio::ip::tcp::socket (service);
acceptor->accept(*clientSock);
std::cout << "New client joined! " << std::endl;
Client* new_client = new Client; //create new client
new_client->clientSock = clientSock;
new_client->last_read_request = "";
new_client->activity = TRUE;
new_client->request_thread = new boost::thread(&Server::HandleRequest, this, new_client);//new thread with handling client requests
mtx.lock();
clients_list->push_back(new_client);
mtx.unlock();
std::cout << "Total clients:" << clients_list->size() << std::endl;
}
}
新的套接字连接后,新的 HandleRequest 线程开始。变量迭代器用于 ping 与套接字的连接(如果收到来自客户端的任何数据,它会下降到零)。 我的问题是: 在我开始程序之前,我可以在迭代器广告上设置断点,但在它开始后断点被放到 if 语句(“if (Client_to_handle->clientSock->available())”)。此外,如果我在“if (Client_to_handle->clientSock->available())”上设置断点并在那里停止程序,那么调试器会说未定义变量迭代器。并且程序从不点击“else if (iterator >= 10)”它只是通过它来提高睡眠功能。 为什么我不能定义变量,我的程序拒绝看到 else if 语句?
void Server::HandleRequest(Client * Client_to_handle)
{
int iterator = 0;
while (TRUE)
{
if (Client_to_handle->clientSock->available())
{
//do stuff and drop iterator to zero (connection active)
iterator = 0;
}
else if (iterator >= 10) //program refuses to get in here
{
if (iterator == 20)
{
Client_to_handle->clientSock->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
Client_to_handle->clientSock->close();
Client_to_handle->activity = FALSE;
}
boost::asio::write(*Client_to_handle->clientSock, boost::asio::buffer("1|"));
}
boost::this_thread::sleep(boost::posix_time::millisec(1000));
}
}
【问题讨论】:
标签: c++ multithreading boost