我最近做一个多线程多文件传输的东西,在构件框架上想请教下,该如何判断每1个文件结束了,也就是如何判断一次传输结束。还有个奇怪的问题,我用nio的write到channel里了i个字节,但是那边读出来的所有字节不够i个,而且只是中间一部分传输随机发生。下面是部分代码 ,有好的程序最好~~谢谢各位拉。 能帮忙加下qq176781788最好~ 网卡。。打网页慢。。
////////////////////////////////////////////////////////////////////////////server
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
it.remove();
if (key.isAcceptable()) {
System.out.println("Key is Acceptable");
ServerSocketChannel ssc = (ServerSocketChannel) key
.channel();
socket = (SocketChannel) ssc.accept();
socket.configureBlocking(false);
SelectionKey another = socket.register(sel,
SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
if (key.isReadable()) {
System.out.println("Key is readable");
readMessage(key); }public String readMessage(SelectionKey key) {
int nBytes = 0;
ByteBuffer temp = ByteBuffer.allocate(1);
temp.put((byte) 1);
temp.flip();
socket = (SocketChannel) key.channel();
File folder = new File("d:\\"
+ socket.socket().getInetAddress().toString());
if (!folder.exists() || !folder.isDirectory()) {
folder.mkdir();
}
ByteBuffer buf = ByteBuffer.allocate(0x500000 + 16);
byte[] head = new byte[16];
try {
long length=0;
File f = new File(folder, "1");
f.createNewFile();
FileChannel fc = new FileOutputStream(f).getChannel();
buf.clear();
while((nBytes = socket.read(buf))>0){
length+=nBytes;
System.out.println("nbyte=" + nBytes);
buf.flip();
int i = fc.write(buf);
System.out.println("write=" + i);
buf.clear();
}
FileInputStream fis = new FileInputStream(f);
fis.read(head);
System.out.println("name="+new String(head));
System.out.println(socket.write(temp));
fc.close();
fis.close();
key.cancel();
f.renameTo(new File(folder,new String(head)));
System.out.println("length:  "+length);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
///////////////////////////////////////////client
private class SendThread extends Thread {
File ff;
int nBytes;
ByteBuffer temp = ByteBuffer.allocate(1);
SendThread(File ff) {
this.ff = ff;
start();
} public void run() {
try {
makeConnection();
ByteBuffer bytebuf = ByteBuffer.allocate(0x500000 + 16);
FileChannel fc1 = new FileInputStream(ff).getChannel();
fc1.read(bytebuf);
bytebuf.flip();
nBytes=client.write(bytebuf);
bytebuf.clear();
while(true){
if(client.read(temp)>0)break;

}
System.out.println(nBytes);

fc1.close();
client.close();
} catch (IOException e) {
new RuntimeException(e);
}
}
}
每个文件分块都把本机ip和文件名加在头部一起传输

解决方案 »

  1.   

    现在的主要问题是  客户端给服务器传了5m的文件  但是服务器端有时候只接受一部分就没了 
    while((nBytes = socket.read(buf))>0){ 
    length+=nBytes; 
    System.out.println("nbyte=" + nBytes); 
    buf.flip(); 
    int i = fc.write(buf); 
    System.out.println("write=" + i); 
    buf.clear(); 

    谁帮忙解决下 
      

  2.   

    不直接发数据,包装下,如:DATA+数据长度+数据块
    "DATA"是个文本标志,占4字节
    "数据长度"占32个字节
    接收数据的时候,首先解析这个串,验证下"数据长度"是否和"数据块"长度相同,当接收到数据长度为0时,视数据发送完成。
    略改下还可以做到断点续传和数据校验。