JAVASE网络编程之TCP实现传输文件

客户端发送文件,服务端接收后作出响应

public class TCPClientDome02 {
    
    

    public static void main(String[] args) {
    
    
        //设置地址
        try {
    
    
            InetAddress name = InetAddress.getByName("127.0.0.1");

            Socket socket = new Socket(name, 9999);

            //创建一个输出流
            OutputStream os = socket.getOutputStream();
            //3.读取文件
            FileInputStream fis = new FileInputStream(new File("图片.jpg"));

            byte[] buffer = new byte[1024];

            int len;
            while ((len = fis.read(buffer)) != -1) {
    
    
                os.write(buffer, 0, len);
            }

            //通知服务器我已经结束了

            socket.shutdownOutput();

            //确认服务器接收完毕,才能够断开连接
            InputStream is = socket.getInputStream();

            ByteOutputStream boas = new ByteOutputStream();

            byte[] byte2 =new byte[1024];

            int len2;

            while ((len2 =is.read(byte2))!=-1){
    
    
                boas.write(byte2);
            }

            System.out.println(boas.toString());


            //关闭资源

            fis.close();
            os.close();
            socket.close();


        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

}

服务端接收数据,并对客户端做出响应

public class TCPServerDome02 {
    
    

    public static void main(String[] args) {
    
    
        try {
    
    
            ServerSocket serverSocket = new ServerSocket(9999);
            // 2等待客户端连接过来
            Socket accept = serverSocket.accept();
            //获取输入流
            InputStream is = accept.getInputStream();

            //文件输出
            FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));

            int len;
            byte[] buffer = new byte[1024];

            while ((len = is.read(buffer)) != -1) {
    
    
                fos.write(buffer, 0, len);
            }

            //通知客户端我已经接收完毕了
            OutputStream os = accept.getOutputStream();
            os.write("我接收完毕了,你可以关闭了".getBytes());


            fos.close();
            is.close();
            accept.close();
            serverSocket.close();

        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42794826/article/details/108905467
今日推荐