gpt4 book ai didi

Java套接字: unable to send response to client after sending file to server

转载 作者:行者123 更新时间:2023-12-02 09:42:53 28 4
gpt4 key购买 nike

我正在使用 Java Socket 将文件发送到服务器,然后获取响应。问题是每次我尝试从服务器读取响应时,它都会使服务器的文件读取部分挂起。我真的需要你的帮助来了解这里发生的事情吗?

这是服务器代码:

ServerSocket server = new ServerSocket(PORT);
Socket client = server.accept();
BufferedInputStream netInStream = new BufferedInputStream(client.getInputStream());
BufferedOutputStream netOutStream = new BufferedOutputStream(client.getOutputStream());

String outFileName = "output/test";
File outputFile = new File(outFileName);
if (!outputFile.exists()) {
outputFile.getParentFile().mkdirs();
}
FileOutputStream fileOutStream = new FileOutputStream(outputFile);
BufferedOutputStream bufOutStream = new BufferedOutputStream(fileOutStream);

// read file from client and save
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = netInStream.read(buffer)) > 0) {
bufOutStream.write(buffer, 0, bytesRead);
bufOutStream.flush();
Log.line("Bytes read: " + bytesRead);
}
// clean up file IO
// ...

// send response to client
netOutStream.write("File received by server".getBytes());
netOutStream.flush();

// clean up network IO
// ...

客户端代码:

Socket client = new Socket(DOMAIN_SERVER, PORT_SERVER);
BufferedOutputStream netOutStream = new BufferedOutputStream(client.getOutputStream());
BufferedInputStream netInStream = new BufferedInputStream(client.getInputStream());

String inFileName = "input/test";
File file = new File(inFileName);
if (!file.exists()) {
client.close();
return;
}
FileInputStream fileInSream = new FileInputStream(file);
BufferedInputStream bufInStream = new BufferedInputStream(fileInSream);

// read and send file to server
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = bufInStream.read(buffer)) > 0) {
netOutStream.write(buffer, 0, bytesRead);
netOutStream.flush();
Log.line("Bytes sent: " + bytesRead);
}
// clean up file IO
// ...

// read response from server
StringBuilder res = new StringBuilder();
byte[] charBuf = new byte[128];
int msgBytesRead = 0;
while ((msgBytesRead = netInStream.read(charBuf)) > 0) {
res.append(new String(charBuf, 0, msgBytesRead));
}
Log.line(res.toString());

// clean up network IO
// ...

流程是,客户端向服务器发送文件,服务器读取文件并保存到本地存储,然后服务器向客户端发送响应字符串,客户端读取响应并将其打印在屏幕上。

如果代码如上面所示,服务器将不会退出 while 循环并挂起,因此客户端第二个 while 循环也不会读取任何内容并挂起。但是,如果我注释/删除客户端第二个 while 循环,则两个程序都会运行并且不会发生挂起。文件传输也成功。

最佳答案

您的期望是,一旦服务器发送完文件,read 返回时不会有任何数据。这种期望是错误的。如果服务器关闭了 TCP 连接,并且您显示的 flush 不会关闭连接,而只是确保所有缓冲数据都写入,则 read 只会返回没有数据的情况TCP 连接。

这意味着服务器在刷新之后仍然可以发送更多数据,这就是为什么您的客户端卡在读取并等待更多数据的原因。

关于Java套接字: unable to send response to client after sending file to server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56921784/

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