Notice
Recent Posts
Recent Comments
반응형
오늘도 공부
[펌]Transfer a file via Socket 본문
반응형
출처 : http://www.rgagnon.com/javadetails/java-0542.html
A client module connects to a server then a file is sent to the client. This exemple is very simple with no authentication and hard-coded filename!
Thanks to s.gondi for the fix (bos.flush())!
A client module connects to a server then a file is sent to the client. This exemple is very simple with no authentication and hard-coded filename!
First a server module.
import java.net.*;
import java.io.*;
public class FileServer {
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// sendfile
File myFile = new File ("source.pdf");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}
The client module
import java.net.*;
import java.io.*;
public class FileClient{
public static void main (String [] args ) throws IOException {
int filesize=6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket("127.0.0.1",13267);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("source-copy.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
}
}반응형
'자바 > 자바팁' 카테고리의 다른 글
| [JAVA]Socket Image 전송 (6) | 2011.10.26 |
|---|---|
| [펌]Socket을 이용한 서버로 파일 송수신 예제 입니다. (0) | 2011.10.20 |
| [자바]소켓(CLient측) 연결 확인 (1) | 2011.10.20 |
| properties to hashmap (0) | 2011.04.11 |
| 네이버 svn 설치방법 참고 (0) | 2010.12.09 |
