需求:请上传张图片到服务器。
客户端:
public static void main(String[] args) { System.out.println("客户端启动。。。"); try { Socket socket=new Socket("127.0.0.1",8000); File file=new File("d:\\sxt2019\\danta.jpg"); FileInputStream fileInputStream=new FileInputStream(file); OutputStream outputStream=socket.getOutputStream(); byte[] buf=new byte[512]; int len; while((len=fileInputStream.read(buf))!=-1){ outputStream.write(buf, 0, len); } fileInputStream.close(); outputStream.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
服务器:
public static void main(String[] args) { System.out.println("服务器启动。。。"); try { ServerSocket serverSocket=new ServerSocket(8000); Socket accept = serverSocket.accept(); InputStream inputStream=accept.getInputStream(); File file=new File("d:\\sxt2019\\abc\\danta.jpg"); FileOutputStream fileOutputStream=new FileOutputStream(file); int len; byte[] buf=new byte[512]; while((len=inputStream.read(buf))!=-1){ fileOutputStream.write(buf, 0, len); } inputStream.close(); fileOutputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }