본문 바로가기

자바 DB 연동/네트워크

네트워크를 이용한 파일전송

import java.io.FileOutputStream;

import java.io.InputStream;

import java.net.ServerSocket;

import java.net.Socket;


public class FileServer {

public static void main(String[] args) {

String path="c:\\temp\\test.txt"; // 받을 파일명

ServerSocket ss = null;

FileOutputStream fos = null;

try {

// 서버 객체 생성

ss = new ServerSocket(8000);

System.out.println("서버 시작 !!!");

// 클라이언트가 접속하기를 대기

Socket sc = ss.accept();

System.out.println("클라이언트 접속 !!!");

// 소켓에서 보낸 정보를 받을 입력 스트림을 구한다.

InputStream is = sc.getInputStream();

// 저장할 파일출력스트림 객체 생성

fos = new FileOutputStream(path);

System.out.println("파일 다운로드 시작 !!!");

// 보내온 파일 내용을 파일에 저장

byte []b = new byte[512];

int n;

while((n=is.read(b, 0, b.length))>0) {

fos.write(b, 0, n);

System.out.println(n + "bytes 다운로드 !!!");

}

System.out.println("파일 다운로드 끝 !!!");

fos.close();

sc.close();

ss.close();

} catch (Exception e) {

System.out.println(e.toString());

}

}

}



==============================================================================================================


import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;

public class FileClient {
public static void main(String[] args) {
String path="test.txt"; // 보낼 파일명
Socket sc = null;
String host="127.0.0.1";
int port = 8000;
FileInputStream fis = null;
try {
// 소켓 객체 생성
sc = new Socket(host, port);
System.out.println("서버 접속 !!!");
// 소켓에서 보낼 출력 스트림을 구한다.
OutputStream os = sc.getOutputStream();
System.out.println("파일 보내기 시작 !!!");
// 보낼 파일의 입력 스트림 객체 생성
fis = new FileInputStream(path);
// 파일의 내용을 보낸다
byte []b = new byte[512];
int n;
while((n=fis.read(b, 0, b.length))>0) {
os.write(b, 0, n);
System.out.println(n + "bytes 보냄 !!!");
}
System.out.println("파일 보내기 끝 !!!");
fis.close();
sc.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}