Archive for May 2nd, 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