socket建立的客户端服务端-文件传输
client: package com.xiao.socket; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; public class Client1 { public static void main(String[] args) throws Exception { //1.创建一个socket连接 Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000); //2.创建一个输出流 OutputStream outputStream = socket.getOutputStream(); //3.读取文件 FileInputStream fileInputStream = new FileInputStream("D:\\照片\\xiao.jpg"); byte[] buffer = new byte[1024]; int lenth; while ((lenth=fileInputStream.read(buffer))!=-1){ outputStream.write(buffer,0,lenth); } //通知服务器,我已经结束了 socket.shutdownOutput(); //确认服务器接收完毕,才能够断开连接 InputStream inputStream = socket.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer1 = new byte[1024]; int lenth1; while ((lenth1=inputStream.read(buffer1))!=-1){ byteArrayOutputStream.write(buffer1,0,lenth1); } System.out.println(byteArrayOutputStream.toString()); fileInputStream.close(); outputStream.close(); socket.close(); } }
server: package com.xiao.socket; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server1 { public static void main(String[] args) throws Exception { //1.先创建一个端口号 ServerSocket serverSocket = new ServerSocket(9000); //2.等待连接 Socket socket = serverSocket.accept();//阻塞式监听,会一直等待客户端连接 //3.获取输入流 InputStream inputStream = socket.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream("receive.jpg"); byte[] buffer = new byte[1024]; int lenth; while((lenth=inputStream.read(buffer))!=-1){ fileOutputStream.write(buffer,0,lenth); } //通知客户端我接收完毕 OutputStream outputStream = socket.getOutputStream(); outputStream.write("我接收完毕".getBytes()); fileOutputStream.close(); inputStream.close(); socket.close(); } }
微信扫码关注
更新实时通知