【发布时间】:2012-11-30 17:58:17
【问题描述】:
我正在尝试在 2 个 Java 套接字客户端之间建立文件传输机制。发件人客户端将包括此排序 sn-p:
FileInputStream fis = null;
BufferedInputStream bis = null;
BufferedOutputStream outStream = null;
byte[] fileBytes = new byte[(int) file.length()];
int bytesRead = 0;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
outStream = new BufferedOutputStream(socket.getOutputStream());
bytesRead = bis.read(fileBytes, 0, fileBytes.length);
outStream.write(fileBytes, 0, fileBytes.length);
} catch (IOException _IOExc) {
Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE,
null, _IOExc);
//QuitConnection(QUIT_TYPE_DEFAULT);
}
服务器中介看起来像:
public void run() {
assert (outSocket != null);
byte[] bytes = new byte[fileSize];
try {
System.out.println("inStream " + inStream.available());
outStream = new BufferedOutputStream(outSocket.getOutputStream());
inStream.read(bytes, 0, fileSize);
outStream.write(bytes, 0, fileSize);
outStream.flush();
} catch (IOException ex) {
Logger.getLogger(FileTransport.class.getName()).log(Level.SEVERE,
null, ex);
}
}
目标客户端:
public void run() {
try {
System.out.println("Start reading...");
int len = 1024;
BufferedInputStream inStream = new BufferedInputStream
(client.user.getClientSocket().getInputStream());
while ((bytesRead = inStream.read(fileBytes, 0, len)) >
0 && current < fileSize) {
current = current + bytesRead;
System.out.println("current "+ current);
bos.write(fileBytes, 0, bytesRead < len ? bytesRead : len);
}
bos.flush();
bos.close();
} catch (IOException ex) {
Logger.getLogger(ReadFileThread.class.getName()).log(Level.SEVERE,
null, ex);
} catch (InterruptedException e) {
}
}
服务器和目标客户端都提前传递了“fileSize”,现在的问题是服务器端获取的数据略少,客户端B一直从服务器读取8192字节的数据,永远无法退出循环。
非常感谢 凯夫
【问题讨论】:
-
试试 byte[] fileBytes = new byte[fis.availible()];也许 file.length() 返回一个错误的值。为什么你需要转换为 int 呢?文件是文件对象吗?还是字符串?
-
file.length 通常返回 Long.... 读取和发送文件是好的。我只是想知道服务器端
-
哦,所以文件是一个文件对象?你试过 fis.availible() 吗?
-
还没有,但我不认为这种投射会导致精度出错。看起来clientB无法从服务器获取全部数据。没看到你在 clientB 上与 inputStream 竞争
-
痛苦的是服务器端打印 inStream.read(bytes, 0, fileSize) 永远不会返回相同的结果!!!
标签: java swing network-programming thread-safety swingworker