这个简单的例子将演示应用Java实现客户端与服务器端传输文件的方法。
服务器端源代码:
[java] view plaincopyprint?
import java.net.*;
import java.io.*;
public class FileServer {
public static void main (String [] args ) throwsIOException {
// 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();
}
}
}
1 客户端源代码: 2 3 4 [java] view plaincopyprint? 5 import java.net.*; 6 import java.io.*; 7 8 public class FileClient{ 9 public static void main (String [] args ) throws IOException { 10 int filesize=6022386; // filesize temporary hardcoded 11 long start = System.currentTimeMillis(); 12 int bytesRead; 13 int current = 0; 14 // localhost for testing 15 Socket sock = new Socket("127.0.0.1",13267); 16 System.out.println("Connecting..."); 17 18 // receive file 19 byte [] mybytearray = new byte [filesize]; 20 InputStream is = sock.getInputStream(); 21 FileOutputStream fos = new FileOutputStream("source-copy.pdf"); 22 BufferedOutputStream bos = new BufferedOutputStream(fos); 23 bytesRead = is.read(mybytearray,0,mybytearray.length); 24 current = bytesRead; 25 // thanks to A. Cádiz for the bug fix 26 do { 27 bytesRead = 28 is.read(mybytearray, current, (mybytearray.length-current)); 29 if(bytesRead >= 0) current += bytesRead; 30 } while(bytesRead > -1); 31 32 bos.write(mybytearray, 0 , current); 33 bos.flush(); 34 long end = System.currentTimeMillis(); 35 System.out.println(end-start); 36 bos.close(); 37 sock.close(); 38 } 39 }