我正在编写一个发送/接收 xml 的应用程序。
消息由 DOM 生成并定期发送到服务器(每 2 秒一次)。当收到一些消息时(它取决于一些参数,但对于不同的启动是不变的)服务器响应错误:XML document structures must start and end within the same entity
- 可能,接收到的消息结束被切断。有时错误连续出现,有时它们与正常消息混合。
消息正确形成(否则错误可能来自开始)。我想,在某种程度上它与消息长度有关;休息时大约有 9800 个符号。
我还发现了一个类似错误的帖子:SAXParseException: XML document structure must start and end within the same entity,但它与我的不同。
这里是一些代码,可能是我做错了什么。
生成文档类:
public class DOMConstructor {
private Element actions;
Document document = null;
DOMConstructor (String key) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
document = documentBuilder.newDocument();
Element rootElement = document.createElement("request");
document.appendChild(rootElement);
Element token = document.createElement("token");
token.appendChild(document.createTextNode(key));
rootElement.appendChild(token);
Element actions = document.createElement("actions");
rootElement.appendChild(actions);
this.actions = actions;
}
public StreamResult getResultXml (OutputStream out) throws TransformerException, FileNotFoundException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(out);
transformer.transform(domSource, streamResult);
return streamResult;
}
protected void addAction (String fromId, String toId, String droids_num) {
Element action = document.createElement("action");
actions.appendChild(action);
Element from = document.createElement("from");
from.appendChild(document.createTextNode(fromId));
action.appendChild(from);
Element to = document.createElement("to");
to.appendChild(document.createTextNode(toId));
action.appendChild(to);
Element units = document.createElement("unitscount");
units.appendChild(document.createTextNode(droids_num));
action.appendChild(units);
}
}
发送xml:
public void sendData (XMLData xml) throws UnknownHostException, IOException, TransformerException, ParserConfigurationException, SAXException {
conn = new Socket(address, port);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
xml.sendData(out, true);
}