Thursday, August 23, 2007

Peer1

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;

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,128,position);
serverSocket.close();
}


private static void makeFileChannel(String filename) throws FileNotFoundException{
//file,channel 생성
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: