Wednesday, August 22, 2007

Server

import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;

public class Server {
static FileChannel OutputChannel;
static RandomAccessFile OutputFile;
static int divSize = 128;

public static void main(String[] args){

try{

ServerSocketChannel server = ServerSocketChannel.open();
System.out.println("before "+server);
ServerSocket socket = server.socket();
SocketAddress addr = new InetSocketAddress(10001);
System.out.println("[Server]:접속을 기다립니다");
socket.bind(addr);
System.out.println("after " + server);
SocketChannel socketChannel = server.accept();

int position = 10;
//클라이언트에게 position 보내기
byte[] b = new byte[1];
b[0]= (byte) position;
ByteBuffer buf1 = ByteBuffer.allocate(2);
buf1.put(b);
buf1.flip();
socketChannel.write(buf1);
System.out.println("\n"+"# socket write : "+(byte)position);
buf1.clear();

//클라이언트로부터 전송된 파일 읽기
ByteBuffer buf = ByteBuffer.allocate(divSize);
socketChannel.read(buf);
buf.flip();
System.out.print("# socket read :");

//읽은 내용 파일에 쓰기
String filename = "C:\\Documents and Settings\\mina\\test\\Random\\src\\d_server.txt";
RandomAccessFile OutputFile = new RandomAccessFile(filename,"rw");
OutputChannel = OutputFile.getChannel();
OutputChannel.position(position);
OutputChannel.write(buf);
buf.flip();
while(buf.hasRemaining()){
System.out.print((char)buf.get());
}

}catch(Exception e){
System.out.println(e);
}
}
}

No comments: