Java在套接字中执行阻塞



我正在创建一个简单的客户机服务器应用程序,让服务器从客户机接收文件。我几乎实现了所有的东西,但是在执行过程中有一个时刻,代码停止了,不再继续。

我对Java没有太多的经验,所以也许这是一件小事,但我不能弄清楚。

这是服务器中的代码:

public static void receive(String token, String fileName, String filePath) throws IOException{
//Stream for binary data and file transfer
OutputStream out = new FileOutputStream(basePath + filePath  + fileName);
InputStream in = socket.getInputStream();
// Variables 
int bytesRead;
// Bytes for store info to be sent
byte[] buffer = new byte[1024 * 16];
//-------------------------
// Send file 
//------------------------- 
System.out.println("1");
while((bytesRead = in.read(buffer)) > 0){
System.out.println("2");
out.write(buffer, 0, bytesRead);
System.out.println("3");
}
System.out.println("4");
//-------------------------
// End of file transfer
//-------------------------

out.close();
} // send

客户端:

public static void send(Socket socket, String token, String fileName, String filePath) throws IOException{
// Getting the file to send from the file system
File file = new File("C:\" + filePath + "\" + fileName);
// Getting length of the file and creating the buffer
int length = (int) file.length();
byte[] buffer = new byte[length];
// Setting up channels to transfer data
InputStream in = new FileInputStream(file);
OutputStream out = socket.getOutputStream();
// Variables 
int bytesRead;
//-------------------------
// Send file 
//------------------------- 
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
//-------------------------
// End of file transfer
//-------------------------
in.close();
} // send

在服务器部分,当涉及到while循环时,它打印数字1,2,3,但从不打印4。代码停止或类似的事情,不能再继续了。因此,其他由main提供的最终调用将被阻塞。

重复,也许这是一个微不足道的历史问题,但我真的不明白为什么。如果循环是无限的,那么2和3一定被打印了很多次,但它只发生了一次。然后,我真的看不出是什么阻止了Java打印4并让代码继续运行。

如果有人有什么主意,我会非常高兴。谢谢你的建议

在客户端,分配一个足够大的缓冲区来读取整个文件。假设您实际上一次读取文件,那么客户端将在一次写入套接字后退出循环。

但是服务器没有办法知道客户端已经完成了对套接字的写入。套接字客户端未关闭;因此,可能会有更多的数据。

我认为你只需要关闭客户端的套接字。然后服务器将看到一个文件结束符。

如果由于某种原因你不能关闭套接字(也许你需要重新使用相同的连接),那么你必须找到其他方法让服务器知道传入的文件何时完成。一种常见的方法是在文件之前发送文件的长度,作为固定长度的值(例如,4字节或8字节的二进制)。

相关内容

最新更新