import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;
public class Client {
static RandomAccessFile OutputFile;
static FileChannel OutputChannel;
private static void makeSocket(String IP,int Port,int position,int length) throws IOException{
SocketAddress addr = new InetSocketAddress(IP,Port);
SocketChannel socket = SocketChannel.open(addr);
System.out.println("[peer socket]: "+ socket);
sendInfo(socket,position);
readSocket(socket,length,position);
closeSocketChannel(socket);
}
private static void sendInfo(SocketChannel socket,int position) throws IOException{
//Peer에게 position보내기
byte[] b = new byte[1];
b[0]= (byte) position;
ByteBuffer Info = ByteBuffer.allocate(2);
Info.put(b);
Info.flip();
socket.write(Info);
System.out.println("#write Info[To Peer)]:"+(byte)position);
Info.clear();
}
private static void readSocket(SocketChannel socket,int length,int position) throws IOException{
//Peer로부터 전송된 파일 읽기
ByteBuffer readBuf = ByteBuffer.allocate(length);
socket.read(readBuf);
readBuf.flip();
System.out.print("#read [From Peer]:" );
while(readBuf.hasRemaining()){
System.out.print((char)readBuf.get());
}
System.out.print("\n\n");
readBuf.flip();
writeFile(readBuf,position);
}
private static void makeFileChannel(String filename) throws FileNotFoundException{
//file,filechannel 생성
OutputFile = new RandomAccessFile(filename,"rw");
OutputChannel = OutputFile.getChannel();
}
private static void writeFile(ByteBuffer readBuf,int position) throws IOException{
//읽은 내용 파일에 쓰기
OutputChannel.position(position);
OutputChannel.write(readBuf);
readBuf.clear();
}
private static void closeSocketChannel(SocketChannel socket) throws IOException{
socket.close();
}
public static void main(String[] args) {
try{
String filename = "C:\\Documents and Settings\\mina\\test\\Buffer\\src\\a_copy.txt";
makeFileChannel(filename);
makeSocket("127.0.0.1",10001,10,128);
makeSocket("127.0.0.1",10002,0,10);
}catch(Exception e){
System.out.println(e);
}finally{
try{
OutputFile.close();
OutputChannel.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
No comments:
Post a Comment