gpt4 book ai didi

java - 向套接字发送数据时的 ObjectOutputStream 问题

转载 作者:行者123 更新时间:2023-12-02 08:19:15 24 4
gpt4 key购买 nike

我在我的程序中访问服务器,当 cleint 发送消息时,我首先发回一个 1 字节的 ACK,其中 1 字节是我收到的 msgType。

我的程序执行流程是这样的:

        Socket connection = null;
connection = serverSocket.accept();
connection.setKeepAlive(true);
logger.info("server: connection received from " + connection.getInetAddress().getHostName());
out = new ObjectOutputStream(connection.getOutputStream());

.
.

switch(msgType) {
case 0:
// MSG_START

logger.info("Received MSG_START");
// send ACK
sendACK(out, 0);
logger.info("sent ACK for MSG_START");

break;
.

}


Then I have definition of sendAck function:
private static void sendACK(ObjectOutputStream out, int msgIntType) throws IOException {
// TODO Auto-generated method stub

byte[] msgType = new byte[1];
msgType[0] = (byte) (msgIntType & 0xFF);
logger.debug("Sending message to client: " + msgType.toString());
out.write(msgType);
out.flush();
logger.debug("Sending msg: " + Arrays.toString(msgType));
}

现在的问题是,在客户端,当客户端尝试 in.read() 时,它得到的 byteRead 为 -1 而不是 1。

这里可能出现什么问题?

提前致谢,-JJ

最佳答案

ObjectOutputStream 旨在将 Java 对象写入流。在这种情况下,我认为您应该使用 DataOutputStream (客户端也应该如此)。

你会做类似的事情:

dataOutputStream.writeByte(0);

编辑:顺便说一句,客户端应该使用 DataInputStream。

关于java - 向套接字发送数据时的 ObjectOutputStream 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5780437/

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