Peer_2 도 똑같음..ㅋㅋ
토큰안하고 그냥 랭스랑 포지션 같이 보내는걸로 했어요..ㅋㅋ
import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;
public class Peer_1 {
static int Port = 10001;
static FileChannel InputChannel;
static RandomAccessFile InputFile;
static ServerSocketChannel server;
static ServerSocket serverSocket;
static boolean flag = false;
static int length = 0;
static int position = 0;
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();
readInfo(socket);
sendFile(socket);
serverSocket.close();
}
private static void makeFileChannel(String filename) throws FileNotFoundException{
//File,Filechannel 생성
InputFile = new RandomAccessFile(filename,"rw");
InputChannel = InputFile.getChannel();
}
private static void readInfo(SocketChannel socket) throws IOException{
//Client로부터 요청된 position 읽기
ByteBuffer readBuf = ByteBuffer.allocate(3);
socket.read(readBuf);
readBuf.flip();
System.out.print("#read[From Clent]:" );
while(readBuf.hasRemaining()){
System.out.print("Position :"+readBuf.get());
}
readBuf.flip();
System.out.print("\n");
byte[] b = new byte[2];
readBuf.get(b);
System.out.println("P:"+ b[0]+" s:"+ b[1]);
readBuf.clear();
position = b[0];
length = b[1];
}
private static void sendFile(SocketChannel socket) 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