Discovery of the TCP Half-Close


I'm working on a java project at work that has a TCP-based server component that accepts XML messages from clients. I implemented an XML handler that I pass to the SAXParser class that takes the XML as an input stream. The client sends the XML message and then waits for a reply on the same connection. But the input stream isn't closed, so the SAXParse doesn't know when EOF has been reached and my XML handler methods are never called.

Then I discovered (today) that the full-duplex socket connection can be half-closed using the shutdown(2) function call of the socket library. You can shutdown the read or the write side of the socket. So I had the socket close the write side, which signaled EOF to the input stream and allowed the SAXParser to fully parse the message. Cool. Now I have to rearrange my logic a bit to properly queue up the reply message so it gets filled in with the latest bit of outbound data and is sent before we (server and client) close the connection completely.

I just thought I'd mention this because there weren't a ton of examples on how to use this half-close option for TCP connections. But then it turned out there is very little complexity to using it. You simply have to call shutdown(sd, type) (see man 2 shutdown). Pretty simple, really.


update 2006-11-16
Use of a half-close had to be dropped for this project .  It turns out that when my Java server accepts a connection from a client that sends XML, and I pass the InputStream to an instance of the SAXParser class, the parser closes the connection.  I can send data on the connection before calling the SAXParser, but not after, and the only explanation is that the SAXParser is closing the connection.  So we had to punt and switch to using asynchronous, one way messages.