1 | |
package eu.unicore.uftp.rsync; |
2 | |
|
3 | |
import java.io.DataInputStream; |
4 | |
import java.io.DataOutputStream; |
5 | |
import java.io.IOException; |
6 | |
import java.net.Socket; |
7 | |
import java.nio.ByteBuffer; |
8 | |
import java.nio.channels.ByteChannel; |
9 | |
import java.util.ArrayList; |
10 | |
|
11 | |
public class SocketMasterChannel implements MasterChannel{ |
12 | |
|
13 | |
private final Socket socket; |
14 | |
|
15 | 0 | public SocketMasterChannel(Socket socket){ |
16 | 0 | this.socket=socket; |
17 | 0 | } |
18 | |
|
19 | |
@Override |
20 | |
public ChecksumHolder receiveChecksums() throws IOException { |
21 | 0 | DataInputStream dis=new DataInputStream(socket.getInputStream()); |
22 | 0 | ChecksumHolder res=new ChecksumHolder(); |
23 | 0 | res.blocksize=dis.readInt(); |
24 | 0 | int numBlocks=dis.readInt(); |
25 | 0 | res.weakChecksums=new ArrayList<Long>(); |
26 | 0 | res.strongChecksums=new ArrayList<byte[]>(); |
27 | 0 | for(int i=0; i<numBlocks; i++){ |
28 | 0 | res.weakChecksums.add(dis.readLong()); |
29 | 0 | byte[]cs=new byte[16]; |
30 | 0 | dis.readFully(cs); |
31 | 0 | res.strongChecksums.add(cs); |
32 | |
} |
33 | 0 | return res; |
34 | |
} |
35 | |
|
36 | |
@Override |
37 | |
public void sendData(long bytes, ByteChannel source, int index) |
38 | |
throws IOException { |
39 | 0 | DataOutputStream dos=new DataOutputStream(socket.getOutputStream()); |
40 | |
|
41 | 0 | dos.writeInt(index); |
42 | 0 | dos.writeLong(bytes); |
43 | 0 | dos.flush(); |
44 | 0 | if(source==null)return; |
45 | |
|
46 | |
|
47 | 0 | long remaining=bytes; |
48 | 0 | ByteBuffer buf=ByteBuffer.allocate(2048); |
49 | 0 | int len=0; |
50 | 0 | while(len>-1 && remaining>0){ |
51 | 0 | if(remaining<buf.limit()){ |
52 | 0 | buf.limit((int)remaining); |
53 | |
} |
54 | 0 | len=source.read(buf); |
55 | 0 | if(len>0){ |
56 | 0 | buf.flip(); |
57 | 0 | socket.getOutputStream().write(buf.array(),0,len); |
58 | 0 | buf.clear(); |
59 | 0 | remaining-=len; |
60 | |
} |
61 | |
} |
62 | 0 | socket.getOutputStream().flush(); |
63 | 0 | } |
64 | |
|
65 | |
@Override |
66 | |
public void shutdown() throws IOException { |
67 | |
|
68 | 0 | sendData(-1, null, -1); |
69 | 0 | } |
70 | |
|
71 | |
} |