views:

684

answers:

2

I have a problem with Socket connection closing too fast. I was told I need to temporarily load data from Socket and the parse it. Here is my code:

ServerSocket listen = new ServerSocket(this.port);
Socket server;

while(i < this.maxConnections)
{
    server = listen.accept();
    processRequest(server);
    i++;
}

processRequest

protected void processRequest(Socket server) throws IOException
{
    ProcessXML response = new ProcessXML(server.getInputStream());

    new PrintWriter(server.getOutputStream(), true).println("response text");
}

processXML

public ProcessXML(InputStream is)
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(false);

    Document doc = factory.newDocumentBuilder().parse(new InputSource(is));
    ....
}

error

[Fatal Error] :2:1: Premature end of file.
org.xml.sax.SAXParseException: Premature end of file.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at ProcessXML.<init>(ProcessXML.java:22)
at Bank.processRequest(Bank.java:41)
at Bank.listen(Bank.java:25)
at BankStart.main(BankStart.java:6)


Now I could store content of server.GetInputStream() into file and then supply that to DocumentBuilder, but I think its a bad solution. How could I store content to some temporary storage and also be able to supply that to .parse() without closing the socket.

+1  A: 

I think the solution you are using expects the data to be avaible at construct time. You would need to use a stream parser. find a STAX implementation and you should be able to do this

Nuno Furtado
A: 

Doesn't seem like a socket thing... Otherwise you'd see a socket closed exception or something like that. As a test just read the bytes and save it to a text file somewhere, don't worry about building the doc just yet. Check that the file is a properly formed XML and that the encoding matches that specified in the document. Look for any funny characters at the end of the file, could be that the client is inserting some weird EOF character or similar.

CurtainDog
Actually I solved the problem. I simply loaded whole InputStream into String via Scanner and I just supplied that to DocumentBuilder...
FrEaKmAn