【发布时间】:2014-05-24 02:19:52
【问题描述】:
我正在尝试将文本 .txt 文件从客户端简单传输到服务器,无论我认为我知道多少,了解我在做什么,以及到底发生了什么,我总是得到它错了。我真的可以在这里使用一些帮助。
所以,这是代码,两个函数将.txt 文件从一个传输到另一个:
客户端:
private void sendFileToServer(String file_name) throws IOException {
File file=new File(file_name);
int file_size=(int)file.length();
byte[] bytes=new byte[file_size];
FileInputStream os=null;
try {
os = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println("The file "+file+" wasn't found");
return;
}
BufferedInputStream bos=new BufferedInputStream(os);
bos.read(bytes);
output.write(bytes,0,bytes.length);
/* 'output' is a PrintStream object, that holds the output stream
* for the client's socket, meaning:
* output=new PrintStream(client_socket.getOutputStream()); */
output.flush();
bos.close();
}
这会将所有内容缓冲到BufferedInputStream,将其复制到bytes,然后将其发送到另一端——服务器。
服务器端:
public static String receiveFileFromClient(Client client) throws IOException {
int buffer_size=client.getSocket().getReceiveBufferSize();
byte[] bytes=new byte[buffer_size];
FileOutputStream fos=new FileOutputStream("transfered_file.txt");
BufferedOutputStream bos=new BufferedOutputStream(fos);
DataInputStream in=client.getInputStream();
int count;
System.out.println("this will be printed out");
while ((count=in.read(bytes))>0) { // execution is blocked here!
bos.write(bytes, 0, count);
}
System.out.println("this will not be printed");
bos.flush();
bos.close();
return "transfered_file.txt";
}
我的意图是继续从客户端读取字节(while 循环),直到另一端(客户端)没有更多字节要发送,这就是 in.read(bytes) 应该返回 0 的地方并且循环应该中断,但这永远不会发生,它只是被阻塞,即使来自客户端输入流的所有字节都已成功传输!
为什么循环不中断?
来自 Javadoc:
如果由于流位于文件末尾而没有可用字节,则 返回值 -1
最后一个字节不被认为是“文件结尾”吗?我确保函数sendFileToServer 正确地将整个文件写入output 实例(PrintStream 对象)并返回。
任何帮助将不胜感激。
【问题讨论】:
标签: java file client-server