1

与编组和解组读者和作家有问题。所以就在这里。这就是我将某些内容编组到 PrintWriter 的方式。

try {

    JAXBContext jaxbContext = JAXBContext.newInstance(XMLProtocol.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    //jaxbMarshaller.setProperty(, value)
    //jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    jaxbMarshaller.marshal(protocol, out);


} catch (JAXBException e) {
    LOG.error("Error while processing protocol"+e);             
}

这就是我得到它的方式:

private BufferedReader in;
private PrintWriter out;
private String buffer;
private StringBuffer stringBuffer;

public ServerThread(Socket s) throws IOException {
    socket = s;
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
    start();
}

public void run() {
    try {
        while (true) {
            // LOG.trace("Waiting for input stream ready");

            /*
             * if (in.readLine().endsWith(">")) {
             *     LOG.trace("here we go"+buffer);
             *     JAXBContext jaxbContext = JAXBContext.newInstance(XMLProtocol.class);
             *     Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
             *     XMLProtocol protocol = (XMLProtocol) jaxbUnmarshaller.unmarshal(in);
             *     LOG.trace("Nop it no the end " + protocol.getContent());
             * }
             */

            if (in.ready()) {

                LOG.trace("BufferedReader - ready");
                buffer += in.readLine();
                if (buffer.endsWith("</XMLProtocol>")) {
                    LOG.trace("Wish you were here1"+in);

                    JAXBContext jaxbContext = JAXBContext.newInstance(XMLProtocol.class);

                    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

                    XMLProtocol protocol = (XMLProtocol) jaxbUnmarshaller.unmarshal(in);

                    LOG.trace("Getting message from user " + protocol.getContent());
                } else {

                    LOG.trace("Nop it no the end " + buffer);
                }
            }
        }

    } catch (IOException e) {
        e.printStackTrace();

    } catch (JAXBException e) {
        e.printStackTrace();

    } finally {
        try {
            socket.close();
            LOG.trace("Socket closed");
        } catch (IOException e) {
            LOG.error("Socket no closed" + e);
        }
    }
}

然后这个 Unmarshall 操作挂起。它甚至没有向我显示异常。

4

1 回答 1

0

是的,我找到了这个问题的解决方案!JAXB 不是 SOCKET 流的最佳决定,因为它等待流结束。解决方案是使用清晰的 SAX 解析器,您可以在其中编写自己的 ParserHandler (DefaultHandler.class),当您到达最后一个标签时,您应该抛出自己的异常,指示停止解析。

于 2012-06-15T14:00:05.270 回答