package com.baidu.tcp; import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * 服务器端 */ public class ServerDemo1 { public static void main(String[] args) { FileOutputStream fos=null; OutputStream os=null; //建立服务器端套接字 try { ServerSocket ss=new ServerSocket(9999); //监听客户端 Socket socket=ss.accept(); //得到客户端通道输入流 InputStream is=socket.getInputStream(); //建立字节输出流关联文件存储地 fos=new FileOutputStream("h:\\copy.mp4"); //读写存入 byte[] buf=new byte[1024*8]; int len=0; while((len=is.read(buf))!=-1){ fos.write(buf); fos.flush(); } //给客户端以反馈信息 os=socket.getOutputStream(); os.write("文件上传成功!".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally{ try { //关闭资源 os.close(); fos.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } //======================================================= package com.baidu.tcp; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /** * 客户端 */ public class ClientDemo1 { public static void main(String[] args) { //1.获取客户端套接字 Socket socket=null; try { socket=new Socket("localhost",9999); //得到通道输出流 OutputStream os=socket.getOutputStream(); //建立客户端输入流关联上传文件 FileInputStream fis=new FileInputStream("E:\\我的做品\\Lose You.mp4"); byte[] buf=new byte[1024*8]; int len=0; while((len=fis.read(buf))!=-1){ os.write(buf,0,len); os.flush(); } //告知客户端文件上传完毕 socket.shutdownOutput();; //得到服务器端的反馈信息 InputStream is=socket.getInputStream(); byte[] buf1=new byte[1024]; int len1=0; while((len1=is.read(buf1))!=-1){ System.out.println(new String(buf1,0,len1)); } is.close(); } catch (Exception e) { e.printStackTrace(); }finally{ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }