我正在构建一个套接字客户端,在这里我需要实现连接的超时、读、写以及协议本身的超时(缺乏答案等等)。
我正在考虑在一个分离的线程中使用一个简单的计时器,这个线程将在每个事务上启动,然后在事务完成后被取消。同样的方法将用于使用不同超时的协议控制。
要测试的是,我执行了以下简单代码:
#include <string>
#include <sstream>
#include <map>
#include <iostream>
#include <cstring>
#include <thread>
#ifdef _WIN32
#include <io.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <Windows.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <sys/types.h>
#endif
#include <stdio.h>
#include <stdlib.h>
bool timerOn = false;
int currentSocket = 0;
void Timer(int seconds)
{
int tick = seconds;
while (tick > 0)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
tick--;
}
if (timerOn)
close(currentSocket);
}
void StartTimer(int seconds)
{
timerOn = true;
std::thread t(&Timer, seconds);
t.detach();
}
void StopTimer()
{
timerOn = false;
}
void Connect(std::string address, int port)
{
struct addrinfo hints;
struct addrinfo *result = NULL;
struct addrinfo *rp = NULL;
int sfd, s;
std::memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPV4 or IPV6 */
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
std::string portStr;
portStr = std::to_string(port);
s = getaddrinfo(address.c_str(), portStr.c_str(), &hints, &result);
if (s != 0)
{
std::stringstream ss;
ss << "Cannot resolve hostname " << address << gai_strerror(s);
throw std::runtime_error(ss.str());
}
for (rp = result; rp != NULL; rp = rp->ai_next)
{
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1)
continue;
StartTimer(10);
int sts = connect(sfd, rp->ai_addr, rp->ai_addrlen);
StopTimer();
if (sts == 0)
break;
close(sfd);
}
freeaddrinfo(result); /* Object no longer needed */
if (rp == NULL)
{
std::stringstream ss;
ss << "Cannot find server address at " << address << " port " << port;
throw std::runtime_error(ss.str());
}
currentSocket = sfd;
}
int main()
{
try
{
Connect("192.168.0.187", 9090);
std::cout << "Connected to server. Congrats!!!" << std::endl;
}
catch (std::exception& ex)
{
std::cout << "Error connecting to server. Aborting." << std::endl;
std::cout << ex.what() << std::endl;
}
}在计时器上关闭套接字并不会取消“connect”操作,从而迫使它错误地中止。我也试过shutdown(sfd, SHUT_RDWR);但没有成功.
我的方法无效吗?为什么不起作用?
如何从分离的线程中错误地强制connect中止?
发布于 2016-04-14 21:49:12
在计时器上关闭套接字并不会取消“connect”操作,从而迫使它错误地中止。
哇哦!你绝对不能这么做。在关闭套接字时,不可能知道线程实际上在connect中被阻塞(而不是要调用connect)。在一个线程中释放资源,而另一个线程正在或可能使用它,则会造成灾难。
想象一下这样的情况:
connect,因此它会安排超时。connect的线程最终被调度并调用connect --连接库的套接字!灾难。你有两个选择:
connect操作.connect的线程。但我想知道你为什么要烦我。为什么要中止连接?如果在超时之前连接尚未成功,则需要执行其他操作,请继续执行。
https://stackoverflow.com/questions/36634371
复制相似问题