![](/img/trans.png)
[英]ObjectOutputStream not sending data (server stuck at socket.accept())
[英]ObjectOutputStream issue when sending data to a socket
我在我的程序中的服务器上犹豫不决,当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序列化规范中描述的特殊协议。 此类协议受制于实际有效载荷之前发送的某些标头。
因此,最好是使用其他不受这些装饰影响的流。
ObjectOutputStream用于将Java对象写入流。 在这种情况下,我认为你应该使用DataOutputStream(客户端应该这样)。
你会做的事情如下:
dataOutputStream.writeByte(0);
编辑 :BTW,客户端应该使用DataInputStream。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.