서버 클래스
public class FileServerUpLoad {
public static void main(String[] args) {
// 서버단 프로그램
// 1.서버소켓 생성 ServerSocker :
// 클라이언트가 연결하면 Socket을 생성해 주는 Socket Factory : 객체를 만들어주는 것 :Factory
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null; // 소켓으로 받아서is = socket.getInputStream();
FileOutputStream fos = null; // FileOutputStream 파일에다가 출력
try {
// 포트번호를 넣어서 객체를 생성.
serverSocket = new ServerSocket(5000);
} catch (IOException ioe) {
// 5000번 포트가 이미 사용중일 경우 포트충돌 예외발생.
// 5000번 포트가 이미 있으면 더이상 진행할 의미가 없다. 프로그램 종료!
ioe.printStackTrace();
return;
}
while (true) {
// while(true)하기전에는 한명의 Client만 기다리는 프로그램 <- 쓸모없음....ㅋ
try {
System.ou.println("---------------- Client의 접속을 기다립니다...
---------------------");
socket = serverSocket.accept(); // 연결되면 Socket을 리턴!
System.out.println("---------------- Client가 접속을
완료했습니다! ---------------------");
// 3. InputStream이나 OutputStream을 조회.
is = socket.getInputStream();
// 3.1 필터를 연결!!
fos = new FileOutputStream(new File("C:\\Users\\Administrator\\Dropbox"
+"\\JAVA\\workspace\\day30\\file\\carrot33.png"));
// 4. IO작업(출력하는 작업)
byte[] buf = new byte[10000];
int data =0;
while((data=(is.read(buf)))!=-1){
fos.write(buf,0,data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 5.연결닫기 : 늦게 만들어진 친구 먼저 닫아준다.
// 5.1 I/O 닫기
// 5.2 socket 닫기
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// if(pw!=null) pw.close();
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}// end of finally
}// end of while
}// end of main
}// end of SimpleFileServer class
클라이언트 클래스
public class FileClientUpLoad {
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\Administrator\\Dropbox\\JAVA\\workspace\\"
+"day30\\file\\carrot.png";
File file = null;
FileInputStream fis = null; // 파일을 읽는다.
OutputStream os = null; // 소켓에 써준다.
// 1. Socket을 생성 <- IP(String) , port(int) 넘겨줄 것.
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 5000);// localhost
// 2.Socket에서 OutputStream을 조회
os = socket.getOutputStream();
// 필요한 FileInputStream 연결하기.
fis = new FileInputStream(path);
// 3. IO 작업
// 서버에 업로드 하기.
int len = (int) fis.getChannel().size();
byte buf[] = new byte[len];
fis.read(buf); // 파일을 읽음
os.write(buf); // 소켓에다 씀.
} finally {
// 4. 연결 단기
// if(br!=null) br.close();
if (fis != null)
fis.close();
if (os != null)
os.close();
if (socket != null)
socket.close();
}
}
}
반응형
'JAVA > Syntax' 카테고리의 다른 글
| Network 프로그래밍 (0) | 2015.02.23 |
|---|---|
| I/O 입출력 클래스 살펴보기 (0) | 2015.02.12 |
| 예외처리 (Throwable) : Unchecked Exception과 Checked Exception (0) | 2015.02.10 |
| [java.util] Collection과 Map을 이용한 정렬하기(Sort) (0) | 2015.02.09 |
| 제네릭스(Generics) (0) | 2015.02.09 |