【问题标题】:c++ client socket simultaneously connectionc++客户端socket同时连接
【发布时间】:2013-01-09 03:19:41
【问题描述】:

你好我有一个客户端套接字应用程序,它同时连接,在 linux 中有超过 5000 个服务器使用 tcpip,但是当我打开套接字连接时,几乎所有连接,检索错误 Operation now in progress。

这是我的客户端套接字连接代码: 我怎样才能同时做好数千个插座连接??? 对不起我的英语不好。 这是我的代码:

struct sockaddr_in echoserver;
struct sockaddr_in sa_loc;
char aport[64];
int optval = 1;
int sock;

memset(&echoserver, 0, sizeof (echoserver));
echoserver.sin_family = AF_INET;  
echoserver.sin_addr.s_addr = inet_addr(server.c_str()); 
echoserver.sin_port = htons(0);     

SOCKET = socket(AF_INET, SOCK_STREAM, 0);
if (SOCKET == -1)
{
 iLastError = errno;
 strLastError = "Create socket Error : "+string(strerror(errno)); 
 connected = false;
 return connected;
}

struct timeval timeouts, timeoutr;
memset(&timeouts, 0, sizeof(timeouts)); // zero timeout struct before use
timeouts.tv_sec = SendTimeOut/1000;
timeouts.tv_usec = 0;
memset(&timeoutr, 0, sizeof(timeoutr)); // zero timeout struct before use
timeoutr.tv_sec = ReceiveTimeOut/1000;
timeoutr.tv_usec = 0;   
int sockopt = setsockopt(SOCKET, SOL_SOCKET, SO_SNDTIMEO, &timeouts, sizeof(timeouts)); 
if (sockopt == -1) 
{
 printf("%s%s","Set socket Option error : ",strerror(errno));
 iLastError = errno;
 strLastError = "setsockopt Error : "+string(strerror(errno));
}
sockopt = setsockopt(SOCKET, SOL_SOCKET, SO_RCVTIMEO, &timeoutr, sizeof(timeoutr)); // 
if (sockopt == -1) 
{
   printf("%s%s","Set socket Option error : ",strerror(errno));
   iLastError = errno;
   strLastError = "setsockopt Error : "+string(strerror(errno));
}

memset(&sa_loc, 0, sizeof(struct sockaddr_in));
sa_loc.sin_family = AF_INET;
sa_loc.sin_port = htons(0);  //8000
sa_loc.sin_addr.s_addr = inet_addr(SourceIP.c_str());
int bindid = bind(SOCKET, (struct sockaddr *)&sa_loc, sizeof(sa_loc));
if (bindid !=0) 
{
 iLastError = errno;
 strLastError = "Bind Error : "+string(strerror(errno));    
}

int conn = connect(SOCKET, (struct sockaddr *) &echoserver, sizeof(echoserver));

if (conn == -1)
{
 strLastError = "Connect Error : "+string(strerror(errno));   
 connected = false;
}
else {
 connected = true;
}

return connected;

wpp

【问题讨论】:

    标签: c++ linux sockets connection


    【解决方案1】:

    如果您的变量SendTimeOut 小于 1000,那么您的接收超时将为 0,我不确定这是否与设置 O_NONBLOCK 相同,但如果是,那么听起来这是正常过程,而您应该循环直到它成功(或者你得到 EISCONN)或失败并出现不同的错误代码。如果这是有意的,您可能应该明确设置 O_NONBLOCK。

    http://linux.die.net/man/3/connect

    EINPROGRESS 为socket的文件描述符设置了O_NONBLOCK,无法立即建立连接;连接应异步建立。

    ...

    如果无法立即建立连接,并且为套接字的文件描述符设置了 O_NONBLOCK,则 connect() 将失败并将 errno 设置为 [EINPROGRESS],但不应中止连接请求,并且应建立连接异步。在建立连接之前,对同一套接字的后续调用 connect() 将失败并将 errno 设置为 [EALREADY]。

    【讨论】:

      猜你喜欢
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多