当前位置:编程学习 > JAVA >>

java socket 发送多个文件的问题

最近做一个项目需要使用socket发送文件,单个文件很简单,但是多个文件就遇到问题了。先上关键代码:
//发送端、客户端 发送文件代码如下:
private void sendFile(List<String> paths, DataOutputStream out) {
List<File> files = FileList.listFile(paths);
long allLength = FileList.getAllLength(files);
try {
System.out.println("count:" + files.size());
out.writeInt(files.size());
out.writeLong(allLength);
int index = 0;
while (index < files.size()) {
byte[] nameBuf = files.get(index).getAbsolutePath().getBytes("utf-8");
System.out.println("name length:" + nameBuf.length);
out.writeInt(nameBuf.length);
out.write(nameBuf);
out.writeLong(files.get(index).length());
int read;
DataInputStream in = new DataInputStream(new FileInputStream(files.get(index)));
byte[] buf = new byte[8192];
long passLen = 0;
while ((read = in.read(buf)) != -1) {
passLen += read;
System.out.println("passLen:" + passLen);
out.write(buf, 0, read);
}
in.close();
index++;
}
// out.flush();
out.close();
} catch (Exception e) {
// TODO: handle exception
}
}
//接收端、服务器 接收文件关键代码如下:
public void run() {
int bytes = 0;
try {
//mCount 前面获取到的文件数
for (int i = 0; i < mCount; i++) {
int nameLen = mIn.readInt();
System.out.println("nameLen:" + nameLen);//这里第一个文件没问题,第二个文件长度就读去错误了!目前毫无头绪。。。
byte[] nameBuf = new byte[nameLen];
mIn.read(nameBuf);
String path = new String(nameBuf, "utf-8");
File f = new File(path);
File dirs = new File(f.getParent());
if (!dirs.exists()) {
dirs.mkdirs();
}
f.createNewFile();
long singleLength = mIn.readLong();
System.out.println("singleLength:" + singleLength);
long singlePass = 0;
DataOutputStream out = new DataOutputStream(new FileOutputStream(f));
while (true) {
bytes = singleLength - singlePass > 8192 ? 8192 : (int) (singleLength - singlePass);
if (bytes > 8192) {
bytes = 8192;
}
byte[] buffer = new byte[bytes];
mIn.read(buffer, 0 , bytes);
out.write(buffer, 0, bytes);
singlePass += bytes;
System.out.println("singlePass:" + singlePass + "bytes:" + bytes);
if (singlePass >= singleLength) {
break;
}
// out.flush();
}
out.close();
}
mIn.close();
if (mSocket != null && mSocket.isConnected()) {
mSocket.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

单独调试过发送端(接收端一直读取的方法),发送端没有问题(至少上面两个打印消息没问题)。但是接收端读到第二个文件时长度就不对了。有时很大,有时负数。求解。。。

06-27 17:24:25.172: I/TcpServer(5945): nameLen:-816167839
06-27 17:24:25.172: E/TcpServer(5945): error:-816167839 Java socket --------------------编程问答-------------------- --------------------编程问答-------------------- mIn.read(nameBuf);
不一定,nameBuf全都读满了
补充:Java ,  Java相关
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,