gpt4 book ai didi

java - 如何改进从 Socket 读取 XML 的方式

转载 作者:行者123 更新时间:2023-12-02 05:05:28 26 4
gpt4 key购买 nike

我正在开发一个 Java 客户端,它通过套接字连接到服务器并发送/接收 XML 消息。我知道消息的架构是什么。我目前可以使用它,但感觉很困惑,而且我还没有对其进行测试以了解它如何处理从服务器同时发送的多个 XML。

这是代码:

  private static BufferedReader socketIn;
private static PrintWriter socketOut;
private static final String SERVICES_FILE = "/etc/services";

public static void main(String[] args) {
int port = getServicePortByName("Service1", "tcp");
try {
logger.info("Creating socket port with ip: " + InetAddress.getLocalHost() + " and port: " + port);
Socket socket = new Socket(InetAddress.getLocalHost(), port);
socketOut = new PrintWriter(socket.getOutputStream(), true);

String message = createMessageXML("LOGIN");
socketOut.println(message);

socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder inputLine = new StringBuilder();
String tmp;

while (true) {
//loop to keep listening/parsing
while(socketIn.ready()) {
tmp = socketIn.readLine();
inputLine.append(tmp);
}
if(inputLine.length() > 0) {
parseReceivedMessage(inputLine.toString());
}
inputLine.replace(0, inputLine.length(), "");
}

} catch (UnknownHostException ex) {
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
}
}

parseReceivedMessage 方法仅接受 String 并将其转换为 Document 对象。我的问题是,除了使用 StringBuilder 之外,是否有更好或更干净的方法来执行此操作?我最初想将 InputStream 传递给 DOM 构建器解析方法。我看到了一些使用 ByteArray 流的示例,但我遇到了一些问题。如果有任何事情需要澄清,请告诉我。

最佳答案

我强烈建议您围绕 XML 消息设计一个框架协议(protocol)。在每个 XML 消息前添加一个长度值作为前缀,该长度值指定要传输的字节数,然后发送 XML 本身(以字节为单位,而不是字符)。然后接收方可以读取长度,然后读取指定数量的字节并将它们传递给 XML 解析器,然后读取下一个长度,依此类推。例如:

  private static DataInputStream socketIn;
private static DataOutputStream socketOut;
private static final String SERVICES_FILE = "/etc/services";

public static void main(String[] args) {
int port = getServicePortByName("Service1", "tcp");
try {
logger.info("Creating socket port with ip: " + InetAddress.getLocalHost() + " and port: " + port);
Socket socket = new Socket(InetAddress.getLocalHost(), port);
socketIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
socketOut = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

byte[] message = createMessageXML("LOGIN");
socketOut.writeInt(message.length());
socketOut.write(message, 0, message.length());

int len = socketIn.readInt();
if (len > 0)
{
message = new byte[len];
socketIn.readFully(message);
parseReceivedMessage(message);
}

} catch (UnknownHostException ex) {
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
}
}

关于java - 如何改进从 Socket 读取 XML 的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27830819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com