这个简单的例子将演示应用Java实现客户端与服务器端传输文件的方法。
服务器端源代码: 01.import
java.net.*; 02.import
java.io.*; 03.
04.public
class
FileServer { 05.
public
static void
main (String [] args ) throws IOException {
06. // create socket 07.
ServerSocket servsock = new
ServerSocket(13267); 08.
while
(true) { 09. System.out.println("Waiting..."); 10.
11. Socket sock = servsock.accept(); 12.
System.out.println("Accepted connection : "
+ sock); 13.
14. // sendfile 15.
File myFile = new
File ("source.pdf"); 16.
byte [] mybytearray = new
byte [(int)myFile.length()];
17.
FileInputStream fis = new
FileInputStream(myFile); 18.
BufferedInputStream bis = new
BufferedInputStream(fis); 19. bis.read(mybytearray,0,mybytearray.length);
20. OutputStream os = sock.getOutputStream();
21. System.out.println("Sending..."); 22. os.write(mybytearray,0,mybytearray.length);
23. os.flush(); 24. sock.close(); 25. } 26. } 27.}
客户端源代码: 01.import
java.net.*; 02.import
java.io.*; 03.
04.public
class
FileClient{ 05.
public
static void
main (String [] args ) throws IOException {
06.
int filesize=6022386; // filesize temporary hardcoded
07.
08.
long start = System.currentTimeMillis();
09.
int bytesRead;
10.
int current = 0;
11. // localhost for testing 12.
Socket sock = new
Socket("127.0.0.1",13267); 13. System.out.println("Connecting...");
14.
15. // receive file 16.
byte [] mybytearray = new
byte [filesize];
17. InputStream is = sock.getInputStream();
18.
FileOutputStream fos = new
FileOutputStream("source-copy.pdf"); 19.
BufferedOutputStream bos = new
BufferedOutputStream(fos); 20. bytesRead = is.read(mybytearray,0,mybytearray.length);
21. current = bytesRead; 22.
23. // thanks to A. Cádiz for the bug fix
24.
do {
25. bytesRead = 26. is.read(mybytearray, current, (mybytearray.length-current));
27. if(bytesRead >= 0) current += bytesRead;
28. } while(bytesRead > -1); 29.
30.
bos.write(mybytearray, 0
, current); 31. bos.flush(); 32.
long end = System.currentTimeMillis();
33. System.out.println(end-start); 34. bos.close(); 35. sock.close(); 36. } 37.} |
|