【发布时间】:2016-04-15 05:49:12
【问题描述】:
我正在构建一个套接字客户端,我需要在其中实现连接、读取、写入超时以及协议本身的超时(缺少答案等)。
我正在考虑在一个分离线程中使用一个简单的计时器,该计时器将在每个事务上启动,然后在事务完成时取消。同样的方法将用于使用不同超时的协议控制。
为了测试我做了以下简单的代码:
#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;
}
}
在计时器上关闭套接字不会取消“连接”操作,而是强制它因错误而中止。我也试过shutdown(sfd, SHUT_RDWR);,但没有成功...
我的方法无效吗?为什么它不工作?
如何强制connect 在分离线程出错时中止?
【问题讨论】:
-
并非所有平台都允许通过简单地关闭套接字来中断
connect()。 -
@RemyLebeau 我知道没有。有时可能会碰巧发生,但实际上无法保证。 (仅使用常规的
socket、connect、closeAPI,实际上是无法完成的。您需要具有附加功能的 API,例如原子“连接然后解锁”功能。) -
@DavidSchwartz Windows 允许通过关闭套接字来中止
connect()。 -
@RemyLebeau 使用什么 API?使用调试 API 检查另一个线程的堆栈以确认它在
connect中被阻止?你当然不能只用close、closesocket和connect。 -
@DavidSchwartz 我认为他的意思是如果线程 A 在
connect()中被阻塞并且线程 B 在同一个套接字句柄上调用closesocket(),那么connect()将失败并且线程 A 将解除阻塞.