length같이 보내서 Token하는거는 못했어요(position만 보낼수있음ㅋ)..ㅠㅠ
파일이 128까지라면 Client가
Peer_1한테 10~128까지..
Peer_2한테는 0~10까지 요청했어요..
import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;
public class Peer_2 {
static int Port = 10002;
static FileChannel InputChannel;
static RandomAccessFile InputFile;
static ServerSocketChannel server;
static ServerSocket serverSocket;
static boolean flag = false;
private static void makeSocket() throws IOException{
//소켓생성
server = ServerSocketChannel.open();
serverSocket = server.socket();
SocketAddress addr = new InetSocketAddress(Port);
serverSocket.bind(addr);
System.out.println("[Peer1]:" + server + "접속을 기다립니다");
SocketChannel socket = server.accept();
int position = readInfo(socket);
sendFile(socket,10,position);
serverSocket.close();
}
private static void makeFileChannel(String filename) throws FileNotFoundException{
//File,Filechannel 생성
InputFile = new RandomAccessFile(filename,"rw");
InputChannel = InputFile.getChannel();
}
private static int readInfo(SocketChannel socket) throws IOException{
//Client로부터 요청된 position 읽기
ByteBuffer readBuf = ByteBuffer.allocate(2);
socket.read(readBuf);
readBuf.flip();
System.out.print("#read[From Clent]:" );
while(readBuf.hasRemaining()){
System.out.print("Position :"+readBuf.get());
}
System.out.print("\n");
readBuf.clear();
int position = readBuf.get();
return position;
}
private static void sendFile(SocketChannel socket,int length,int position) throws IOException{
//파일읽어 Clietn에게 전송하기
ByteBuffer writeBuf = ByteBuffer.allocate(length);
InputChannel.position(position);
InputChannel.read(writeBuf);
writeBuf.flip();
socket.write(writeBuf);
writeBuf.flip();
while(writeBuf.hasRemaining()){
System.out.print((char)writeBuf.get());
}
System.out.print("\n");
writeBuf.clear();
}
public static void main(String[] args){
try{
while(!flag){
String filename = "C:\\Documents and Settings\\mina\\test\\Buffer\\src\\a.txt";
makeFileChannel(filename);
makeSocket();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
serverSocket.close();
server.close();
InputFile.close();
InputChannel.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
No comments:
Post a Comment