在连接失败重用socket描述 [英] Reusing socket descriptor on connection failure

查看:92
本文介绍了在连接失败重用socket描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的客户code,我下面这些步骤连接到插座:

In my client code, I am following these steps to connect to a socket:


  1. 创建一个套接字

  1. Creating a socket

sockDesc = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)  


  • 连接它(在失败的情况下重试'x'的时间)

  • Connecting it (retry for 'x' time in case of failure)

    connect(sockDesc, (sockaddr *) &destAddr, sizeof(destAddr))  
    

    (填充 DESTADDR 字段后)

    使用了)的插座发送( / 的recv()操作:

    send(sockDesc, buffer, bufferLen, 0)  
    recv(sockDesc, buffer, bufferLen, 0)  
    


  • 的close()套接字描述符和退出

    close(sockDesc)  
    


  • 如果在发送() / 的recv()连接中断,我发现我可以通过返回连接步骤2。

    If during send()/recv() the connection breaks, I found that I could connect by returning to step 2.

    这是解决好吗?我应该关闭套接字描述符并返回步骤1?

    Is this solution okay? should I close the socket descriptor and return to step 1?

    这是我无法理解另一个有趣的现象是,当
    我停下我的回声服务器,并启动客户端。我创建一个Socket(步骤1)和呼叫连接()这失败(如预期),但后来我一直在呼唤连接(),可以说,10倍。 5重试后,我开始在服务器和连接()是成功的。但在发送()称它为接收 SIGPIPE 错误。我想知道:

    Another interesting observation that I am not able to understand is when I stop my echo server and start the client. I create a Socket (step 1) and call connect() which fails (as expected) but then I keep calling connect(), lets say, 10 times. After 5 retries I start the server and connect() is successful. But during the send() call it receives SIGPIPE error. I would like to know:

    1)我需要每次连接()无法创建一个新的插座?按我的理解,只要我还没有进行任何发送() / 的recv()插槽上是像新的一样好,我可以重复使用相同 FD 连接()电话。

    1) Do I need to create a new socket every time connect() fails? As per my understanding as long as I have not performed any send()/recv() on the socket it is as good as new and I can reuse the same fd for the connect() call.

    2)我不明白为什么 SIGPIPE 当服务器是涨是收到连接()是成功的。

    2) I don't understand why SIGPIPE is received when the server is up and connect() is successful.

    推荐答案

    是的,你应该关闭并返回到第1步:

    Yes, you should close and go back to step 1:

    close()关闭一个文件描述符,
      这样它不再是指任何
      文件,并可以重复使用。

    close() closes a file descriptor, so that it no longer refers to any file and may be reused.

    这篇关于在连接失败重用socket描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆