這個簡單的例子將示範應用Java實現用戶端與伺服器端傳輸檔案的方法。
伺服器端原始碼:
import java.net.*;<br />import java.io.*;<br />public class FileServer {<br /> public static void main (String [] args ) throwsIOException {<br /> // create socket<br /> ServerSocket servsock = new ServerSocket(13267);<br /> while (true) {<br /> System.out.println("Waiting...");<br /> Socket sock = servsock.accept();<br /> System.out.println("Accepted connection : " + sock);<br /> // sendfile<br /> File myFile = new File ("source.pdf");<br /> byte [] mybytearray = new byte [(int)myFile.length()];<br /> FileInputStream fis = new FileInputStream(myFile);<br /> BufferedInputStream bis = new BufferedInputStream(fis);<br /> bis.read(mybytearray,0,mybytearray.length);<br /> OutputStream os = sock.getOutputStream();<br /> System.out.println("Sending...");<br /> os.write(mybytearray,0,mybytearray.length);<br /> os.flush();<br /> sock.close();<br /> }<br /> }<br />}
用戶端原始碼:
import java.net.*;<br />import java.io.*;<br />public class FileClient{<br /> public static void main (String [] args ) throws IOException {<br /> int filesize=6022386; // filesize temporary hardcoded<br /> long start = System.currentTimeMillis();<br /> int bytesRead;<br /> int current = 0;<br /> // localhost for testing<br /> Socket sock = new Socket("127.0.0.1",13267);<br /> System.out.println("Connecting..."); </p><p> // receive file<br /> byte [] mybytearray = new byte [filesize];<br /> InputStream is = sock.getInputStream();<br /> FileOutputStream fos = new FileOutputStream("source-copy.pdf");<br /> BufferedOutputStream bos = new BufferedOutputStream(fos);<br /> bytesRead = is.read(mybytearray,0,mybytearray.length);<br /> current = bytesRead;<br /> // thanks to A. Cádiz for the bug fix<br /> do {<br /> bytesRead =<br /> is.read(mybytearray, current, (mybytearray.length-current));<br /> if(bytesRead >= 0) current += bytesRead;<br /> } while(bytesRead > -1); </p><p> bos.write(mybytearray, 0 , current);<br /> bos.flush();<br /> long end = System.currentTimeMillis();<br /> System.out.println(end-start);<br /> bos.close();<br /> sock.close();<br /> }<br />}