My (mostly technical) blog 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 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));
outputter = new XMLOutputter();
.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 =
new StringReader(xml));
Now to make it easier on everyone, I attached the source code. Run the ServerThread first and then run the ClientMain.


4 Responses to " hangs when reading from a Socket"

Thanks for a good article,

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


big thanks!

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


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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Ahmed Sabbour's Facebook profile
May 2007
« Apr   Nov »


Error: Twitter did not respond. Please wait a few minutes and refresh this page.

RSS StackOverflow

Recently bookmarked

%d bloggers like this: