【发布时间】:2018-02-25 02:37:40
【问题描述】:
我正在编写一个程序,该程序具有客户端和服务器,客户端将在其中向服务器发送 img 文件。下面的代码适用于服务器,它会在上次运行时从obIn.read 阻塞在while 循环上,因此它永远无法返回-1 并中断循环。它确实打破了我的客户的循环。所以我试图在客户端循环之后刷新它,但它似乎没有任何好处。我不想关闭 obOut,因为这将关闭我想要保持打开的套接字。服务器端是它从 obIn(作为实例变量的输入流)接收数据并将其写入我创建的文件的地方。
//server receives file
File file = new File("image/image.png");
BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file));
byte[] bytes = new byte[1000];
int c = 0;
while((c = obIn.read(bytes)) != -1) {
fileOut.write(bytes, 0, c);
fileOut.flush();
System.out.println(c);
}
System.out.println(c);
fileOut.close();
System.out.println("File Created");
//Client
String imgPath = in.nextLine();
File file = new File(imgPath);
BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[1000];
int c = 0;
while((c = fileIn.read(bytes)) != -1) {
obOut.write(bytes, 0, c);
obOut.flush();
System.out.println(c);
}
obOut.write(bytes, 0, 1000);
obOut.flush();
System.out.println(c);
fileIn.close();
System.out.println("File Sent");
此图像是服务器在顶部,客户端在底部的输出。这就是我发现服务器卡住的地方。
Here 是我找到此方法并尝试使其适用于我的设置的地方。这是我第一次使用流。
【问题讨论】:
-
要发送
-1,你需要close() writer(这里是obOut)。如果您不想这样做,假设您想发送许多文件,那么您需要创建自己的 protocol(客户端和服务器之间的对话规则)。这样的协议应该声明,首先你通知服务器它应该期望多少字节(文件长度),然后不是等待 -1,你只是简单地计算有多少字节到达,在所有字节都被接收之后,服务器可以做其他事情,或等待有关它应该处理的其他任务的信息(例如接收另一个文件)。
标签: java file bufferedinputstream bufferedoutputstream