gpt4 book ai didi

java - 我如何识别网络应用程序的多个命令(Java)

转载 作者:行者123 更新时间:2023-11-30 11:35:07 25 4
gpt4 key购买 nike

我想构建一个客户端-服务器-应用程序来进行一些练习。我从一个简单的聊天开始,这并不难。我还可以通过简单地拆分一个字符串来识别不同的命令,例如“命令:消息”。但我认为这可能有点不方便。所以我想知道是否有更好的方法来实现这一点。我偶然发现了那一边: http://www.javaworld.com/jw-01-1997/jw-01-chat.html?page=6最后它说:

An alternative, however, and much more elegant solution, is to abstract the protocol behind a set of stream classes. The specifics of header construction and insertion can be handled automatically by the stream classes, and the client is then left with much the same interface as before: Clients write messages to a stream, but instead of flushing the stream, they call a method that attaches appropriate headers and sends the encapsulated message.

我真的不知道那是什么意思。有人可以解释一下,或者更好的是,给我一个代码示例。也许还有其他方法可以做?

最佳答案

假设您要发送封装为您发送的链接的消息:

|编号 |伦 |留言内容|.

“抽象一组流类背后的协议(protocol)”的意思是创建扩展流类的类,这些类将为您在封装的消息上放置正确的 ID 和长度。

例如,对于发送两种消息的扩展 PrintWriter:

ID 1 - 普通消息。

ID 2 - 错误信息。

class MyProtocolPrintWriter extends PrintWriter {

public static final int NORMAL_MESSAGE = 1;
public static final int ERROR_MESSAGE = 2;

//put the constructor

public void writeMessage(String message) {
println(
String.format(
"%02x%02d%s", NORMAL_MESSAGE, message.length(), message));
}

public void writeErrorMessage(String message) {
println(
String.format(
"%02x%02d%s", ERROR_MESSAGE, message.length(), message));
}

}

关于java - 我如何识别网络应用程序的多个命令(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15277097/

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