Peer1,2 는 그대로.. Client만 쓰레드로 바꾸어줬음..근데 이렇게 하면 제대로 되기는하는데요..
첫번째줄이 만약 에러 나면 두번째줄 이 실행왠지 안되는거같아요...ㅠㅠ
그럼 쓰레드 만든게 아닌가요?ㅋ 어트케 테스트 해봐야할지요..ㅠㅠㅠㅠㅠㅠ
import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;
public class Client_Th {
static RandomAccessFile OutputFile;
static FileChannel OutputChannel;
class Client_thread extends Thread{
private Client_thread(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,length);
readSocket(socket,length,position);
closeSocketChannel(socket);
}
private void sendInfo(SocketChannel socket,int position,int length) throws IOException{
byte[] b = new byte[2];
b[0]= (byte) position;
b[1]= (byte) length;
ByteBuffer Info = ByteBuffer.allocate(b.length);
Info.put(b);
Info.flip();
socket.write(Info);
System.out.println("#write Info[To Peer)]:"+ b[0]+ " " + b[1]);
Info.clear();}
private 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 void writeFile(ByteBuffer readBuf,int position) throws IOException{
//읽은 내용 파일에 쓰기
OutputChannel.position(position);
OutputChannel.write(readBuf);
readBuf.clear();
}
private void closeSocketChannel(SocketChannel socket) throws IOException{
socket.close();
}
}
private static void makeFileChannel(String filename) throws FileNotFoundException{
OutputFile = new RandomAccessFile(filename,"rw");
OutputChannel = OutputFile.getChannel();
}
public void send(String IP,int Port,int position,int length) throws IOException{
Client_thread ct = new Client_thread(IP,Port,position,length);
ct.start();
}
public static void main(String[] args) {
try{
String filename = "C:\\Documents and Settings\\mina\\test\\Buffer\\src\\a_copy.txt";
makeFileChannel(filename);
new Client_Th().send("127.0.0.1",10001,10,110);
new Client_Th().send("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();
}
}
}
}