gpt4 book ai didi

java - 套接字的输入字节流包装在两种不同的流类型中?

转载 作者:行者123 更新时间:2023-12-02 08:29:35 25 4
gpt4 key购买 nike

我正在尝试实现这样一个协议(protocol):

Client side: 1) client sends     command (String) 2) client sends     object 3) client receives  object or data   [depends on command]Server side: 1) server reads     command (String) 2) server receives  object           [type depends on command] 3) server sends     object or data   [depends on command]

On client side, I'm doing something like this (program blocks on line, marked with "!!!"):

/** Retrieves required wrapper streams */
private void getSocketStreams() {
try {
inputStream = new DataInputStream(
connection.getInputStream());

/* !!! here is a problem: can I do next line's stuff? */
inputObjectStream = new ObjectInputStream(
connection.getInputStream());

outputWriter = new BufferedWriter(
new OutputStreamWriter(
connection.getOutputStream()));
outputObjectStream = new ObjectOutputStream(
connection.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}

/** "put" command processor */
private int processCmdPut(OrderInfo orderInfo) {

/* Send command to peer */
try {
outputWriter.write("put");
outputWriter.newLine();
outputWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}

/* Send inserted object to peer */
sendObject(orderInfo);

/* Get from peer inserted info id */
int id = -1;
try {
id = inputStream.readInt();
} catch (IOException e) {
e.printStackTrace();
}
return id;
}


/**
* Sends object to peer.
* @param obj object to send.
*/
public void sendObject(Object obj){
try {
outputObjectStream.writeObject(obj);
outputObjectStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}

服务器端操作镜像客户端。

关于line的问题,标有“!!!”:是否可以包装socket的字节流使用两个不同的高级流并轮流读/写它们(一一)?我错了吗?我的理解有误吗?

最佳答案

缓冲往往会使使用不同的装饰器链变得困难。您确实不想在同一流上混合文本和二进制数据。我建议以与二进制数据相同的格式编写文本。

关于java - 套接字的输入字节流包装在两种不同的流类型中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3751701/

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