[jdom-interest] Build from Socket

Joseph Bowbeer jozart at csi.com
Wed Nov 19 01:24:00 PST 2003


Sebastian,

This FAQ entry explains why sending the socket input stream directly to the
XML parser is a bad idea if you intend to reuse the socket connection:

 http://jdom.org/docs/faq.html#a0340

What it doesn't say (as Laurent points out) is how to extract the XML data
from the socket input stream.  For that you need some kind of envelope
protocol.  Something like HTTP with a Content-Length header, say, or a
special delimiter.

The problem with your getRequestData method is that stream.read won't
return -1 until the stream is closed (on the sender-side).  Catch 22.

--- original message ---
From: Sebastian Robertsson <sebastian.robertsson at spray.se>
To: jdom-interest at jdom.org
Subject: [jdom-interest] Build from Socket

Hi everyone!

I know this is an old topic - the problem of building a JDOM-doc read from a
socket without closing it.
I've just tried this solution:

http://www.servlets.com/archive/servlet/ReadMsg?msgId=340949&listName=jdom-interest

But, I can't make it work.

On the "sender-side" I use a BufferedOutputStream, and I flush the stream
after sending.
On the receiving side, this is the code:

 byte[] data = getRequestData(clientSocket.getInputStream());
 InputStream in = new ByteArrayInputStream(data);
 Document d = getXMLDocument(in);

 private byte[] getRequestData(InputStream stream) throws IOException {
   byte[] data = null;
   // Content length not specified.
   // => Read content stream until an EOF is encountered.
   ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
   int l;
   byte[] xfer = new byte[1024];
   while ((l = stream.read(xfer)) != -1) {
     baos.write(xfer, 0, l);
   }
   data = baos.toByteArray();
   return data;
 }

 I get everything to work when I close the stream on the sending side, but
when I'm not closing it it seems like this code doesn't work after all.
Though, as far as I can tell, the XML-doc that I'm sending is alright (it
gets parsed correcty when using the close stream-trick, and I can write it
to a file and open without problems). Can somebody help me with this,
please. Any other solutions, or have I missed something in Laurent Bihanic's
solution?

 Regards,

 Sebastian




More information about the jdom-interest mailing list