使用socket上传文件(经典珍藏版)

77 阅读1分钟

1客户端:使用FileInputStream把文件读到内存,使用socket的OutputStream发送文件到ServerSocket服务端

package facepeople.tcp;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ClientTcp {
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("a.jpg");

            Socket socketClient = new Socket("localhost", 6668);
            OutputStream outputStream = socketClient.getOutputStream();
            byte[] bytes1 = new byte[10 * 1024];
            int length1;
            while ((length1=fileInputStream.read(bytes1))!=-1){
                outputStream.write(bytes1,0,length1);
            }
            socketClient.shutdownOutput();
            System.out.println("文件发送完毕" );



//            解析服务端回写的数
            InputStream inputStream = socketClient.getInputStream();
            int length;
            byte[] bytes = new byte[1024];
            while ((length=inputStream.read(bytes))!=-1){
                System.out.println("服务端传来的数据--> " + new String(bytes,0,length));
            }
            fileInputStream.close();
            inputStream.close();
            outputStream.close();
            socketClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2服务端:使用ServerSocket的InputStream获取到客户端传来的数据,使用FileOutputStream写到服务端的硬盘上。

package facepeople.tcp;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ServiceTcp {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(6668);
            Socket acceptSocket = serverSocket.accept();
            InputStream inputStream = acceptSocket.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream("a3.jpg");
            int length;
            byte[] bytes = new byte[10*1024];
//            length=inputStream.read(bytes);
            while ((length=inputStream.read(bytes))!=-1){
                System.out.println("客户端传来的数据 = "+length  );
//                System.out.println("客户端传来的数据 = " +new String(bytes,0,length) );
                fileOutputStream.write(bytes,0,length);
            }
//            服务端回写数据
            OutputStream outputStream = acceptSocket.getOutputStream();
            outputStream.write("客户端你好,服务端文件已保存".getBytes(StandardCharsets.UTF_8));
            outputStream.close();
            inputStream.close();
            serverSocket.close();
        } catch (IOException e) {
            System.out.println("e = " + e.getMessage());
            e.printStackTrace();
        }

    }
}