我设置了一个客户端和服务器套接字。当我使用类ObjectOutputStream和ObjectInputStream以及方法readObject/writeObject时,一切都很好。
它模拟了与一个机器人的通信,我确信这个机器人只会正确解释方法数据输出流.writeBytes.
因此,我建立了新的模拟架构,因为机器人不能每天进行测试。
在以下代码中,ObjectOutputStream/ObjectInputStream readObject/writeObject被DataInputStream/DataOutputStream writeBytes和IOutils.toByteArray替换。服务器套接字正确地接收到消息,但当它试图写回响应时,我会得到一个断开的管道,就好像连接在某个地方关闭了一样。请注意,我从不关闭套接字或流,因为机器人即使在30秒后也可以回答。如果能为DataOutputStream.writeBytes提供任何帮助,我们将不胜感激。
这是非工作代码:
客户:
Socket serverSocket = new Socket("server", 9899);
DataOutputStream outputStream = new DataOutputStream(serverSocket.getOutputStream());
//ObjectOutputStream outputStream = new ObjectOutputStream(serverSocket.getOutputStream());
//outputStream.writeObject("n" + "message" + "r");
outputStream.writeBytes("n" + "message" + "r");
outputStream.flush();
DataInputStream inputStream = new DataInputStream(serverSocket.getInputStream());
//ObjectInputStream inputStream = new ObjectInputStream(serverSocket.getInputStream());
byte [] bytes = IOUtils.toByteArray(inputStream);
String serverResponse = new String(bytes,"UTF-8");
// String serverResponse = (String)inputStream.readObject();
服务器:
ServerSocket serverSocket = new ServerSocket(9899);
while (true) {
Socket socket = serverSocket.accept();
//ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
byte [] bytes = IOUtils.toByteArray(inputStream);
String message = new String(bytes,"UTF-8");
//String message = (String) inputStream.readObject();
Thread.sleep(15000);
//ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
//outputStream.writeObject("server response");
outputStream.writeBytes("server response"); //EXCEPTION THROWN HERE FOR BROKEN PIPE
outputStream.flush();
}
感谢您抽出时间
IOUtils.toString(InputStream)必须读取流直到流结束,这意味着对等方已断开连接。所以你不能写信给它。
如果要用数据流交换字符串,则应该使用writeUTF()和readUTF(()。
或者使用BufferedReader/Writer读取和写入行。