创建服务端:
public class FileServer02 extends Thread{private File source;private Socket s;public FileServer02(File source, Socket s) {super();this.source = source;this.s = s;}@Overridepublic void run() {try {System.out.println(\"向\" + s.getInetAddress().getHostAddress() + \"传输……\");// 获取源文件的输入流InputStream in = new FileInputStream(source);// 获取socket的输出流OutputStream out = s.getOutputStream();// 传输TransferUtils.transfer(in, out);System.out.println(s.getInetAddress().getHostAddress() + \"传输完成\");} catch (Exception e) {e.printStackTrace();} finally {try {if (s != null)s.close();} catch (IOException e) {e.printStackTrace();}}}public static void main(String[] args) throws IOException {// 准备需要传输的文件对象File target = new File(\"\");//在指定端口创建服务ServerSocket server = new ServerSocket(6666);while(true) {Socket s = server.accept();//创建文件传输的线程并启动new FileServer02(target,s).start();}}}
创建客户端:
public class FileClient {public static void main(String[] args) throws UnknownHostException, IOException {File f = new File(\"D:\\\\测试\\\\第二级目录2\\\\a.mp4\");try(//连接知道ip指定端口服务Socket s = new Socket(\"192.168.7.141\",6666);//获取基于Socket的输入流并包装为缓冲流BufferedInputStream bis = new BufferedInputStream(s.getInputStream());BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));){System.out.println(\"开始接收……\");int b = 0;while ((b = bis.read()) != -1) {bos.write(b);}System.out.println(\"接收完成完成\");}catch (Exception e) {e.printStackTrace();}}}