My (mostly technical) blog

SAXBuilder.build() hangs when reading from a Socket

Posted on: May 2, 2007

Yesterday when I was trying to send an XML document through a Socket in a Java program, I was having a lot of trouble in parsing the document when the receiver gets it. The parser was hanging. After a lot of research, I found out that the SAXBuilder.build() method needs an end of file (EOF) signal in order to finish parsing. Since I was passing the message to be parsed through an InputStream of a socket, it obviously had no EOF!

To cut a long story short, if you need to use JDOM to produce XML documents and then send them over a socket and rebuilding them at the receiver, do the following:

Sender side:
Socket serverSocket = new Socket(“localhost”, 7803);
out = new BufferedWriter(new PrintWriter(serverSocket.getOutputStream(),true));
XMLOutputter
outputter = new XMLOutputter();
outputter
.output(doc, out);

Receiver side:
ServerSocket server = new ServerSocket(7803);
Socket incoming = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream());
in.readLine(); // Skip the XML preamble (<?xml … >
String xml = in.readLine();
SAXBuilder parser =
new SAXBuilder();
Document doc = parser.build(
new StringReader(xml));
Now to make it easier on everyone, I attached the source code. Run the ServerThread first and then run the ClientMain.
http://www.pioneersawg.com/sabbour/Client.java
http://www.pioneersawg.com/sabbour/ClientMain.java
http://www.pioneersawg.com/sabbour/ServerThread.java

Advertisements

4 Responses to "SAXBuilder.build() hangs when reading from a Socket"

Thanks for a good article,

I had also the same problem, so u really helped med out!

shakil

big thanks!

you may also want to check out vtd-xml, the latest and most advanced xml processing model

vtd-xml

Today, I went to the beach front with my children. I found a
sea shell and gave it to my 4 year old daughter and said
“You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed.

There was a hermit crab inside and it pinched her ear. She never wants to go back!
LoL I know this is entirely off topic but I
had to tell someone!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Ahmed Sabbour's Facebook profile
May 2007
S M T W T F S
« Apr   Nov »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Tweets

RSS StackOverflow

Recently bookmarked

%d bloggers like this: