Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting to closed TCP/IP connection hangs
    text
    copied!<p>My TCP/IP client hangs while writing to socket. This happens even if server properly closes an accepted connection with <code>close()</code> (or with <code>shutdown()</code>) call. I've always thought that write should return with ECONNRESET error for this case. </p> <p>How do i prevent hang ups in synchronous output? Or rather what am I doing wrong so that an error is not reported by <code>write()</code>?</p> <p>Should I use <code>send()</code> instead of <code>write()</code> or they are interchangeable?</p> <p>I'm testing networking in a separate application with two threads. Main thread starts server thread, that accepts connection and immediately closes it. Main thread then imitates client behavior by connecting to listening port.</p> <p>Main thread code:</p> <pre><code>sockaddr_in serv_addr; bzero((char *) &amp;serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port); int s = socket(AF_INET, SOCK_STREAM, 0); if (bind(s, (sockaddr*)(&amp;serv_addr), sizeof(serv_addr)) &lt; 0) { close(s); throw runtime_error(strerror(errno)); } listen(s,1); start_thread(s); // posix thread accepting a connection on s is started here //Code below imitates TCP/IP client struct hostent *hp; struct sockaddr_in addr; if((hp = gethostbyname(host.c_str())) == NULL){ throw HErrno(); } bcopy(hp-&gt;h_addr, &amp;addr.sin_addr, hp-&gt;h_length); addr.sin_port = htons(port); addr.sin_family = AF_INET; int _socket = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (_socket &lt; 0) { throw Errno(); } assert(ENOTCONN==107); assert(_socket&gt;=0); if(::connect(_socket, (const struct sockaddr *)&amp;addr, sizeof(struct sockaddr_in)) == -1){ throw Errno(); } while(true) { const char a[] = "pattern"; if (write( _socket, a, 7)&lt;0) // Writes 30000 times, then hangs break; } </code></pre> <p>Server thread code:</p> <pre><code>int connection = accept(s); close(connection); </code></pre> <p><strong>EDIT:</strong> The problem reduced to my programming error. It seems I've failed to start accepting thread properly.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload