zoukankan      html  css  js  c++  java
  • Java中Socket通信-客户端向服务端发送照片

    场景

    Java中Socket通信-服务端和客户端双向传输字符串实现:

    https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108488556

    在上面实现服务端与客户端双向的通信传输字符串之后,客户端怎样向服务端发送照片。

    注:

    博客:
    https://blog.csdn.net/badao_liumang_qizhi
    关注公众号
    霸道的程序猿
    获取编程相关电子书、教程推送与免费下载。

    实现

    首先在服务端的java项目中新建一个接收照片的方法

        //服务端接收来自客户端发送的照片
        public static void getImageFromClient() throws IOException {
            byte[] byteArray = new byte[2048];
            ServerSocket serverSocket = new ServerSocket(8088);
            Socket socket = serverSocket.accept();
    
            InputStream inputStream = socket.getInputStream();
            int readLength = inputStream.read(byteArray);
    
            FileOutputStream imageOutputStream = new FileOutputStream(new File("D:\badao.png"));
            while (readLength !=-1)
            {
                imageOutputStream.write(byteArray,0,readLength);
                readLength = inputStream.read(byteArray);
            }
            imageOutputStream.close();
            inputStream.close();
            socket.close();
            serverSocket.close();
        }

    然后在main方法中调用该方法。

    这里指定的照片的路径就是获取服务端发来之后存储的路径。

    然后在客户端新建发送照片的方法

       //客户端发送照片到服务端
        public static void sendImageToServer() throws IOException {
            String imageFile = "C:\Users\admin6\Desktop\gzh.png";
            FileInputStream imageStream = new FileInputStream(new File(imageFile));
            byte[] byteArray = new byte[2048];
    
            System.out.println("socket begin =" + System.currentTimeMillis());
            Socket socket = new Socket("localhost",8088);
            System.out.println("socket end ="+System.currentTimeMillis());
    
            OutputStream outputStream = socket.getOutputStream();
    
            int readLength = imageStream.read(byteArray);
            while (readLength!=-1)
            {
                outputStream.write(byteArray,0,readLength);
                readLength = imageStream.read(byteArray);
    
            }
            outputStream.close();
            imageStream.close();
            socket.close();
        }

    这里的图片路径是要发送给服务端的照片的路径。

    然后在main方法中调用该方法。

    首先运行服务端的main方法,然后运行客户端的main方法,之后去D盘下就会接收到bao.png这张照片了。

    博客园: https://www.cnblogs.com/badaoliumangqizhi/ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。
  • 相关阅读:
    javaweb web.xml文件详解
    Android 屏幕旋转 处理 AsyncTask 和 ProgressDialog 的最佳方案
    系统环境搭建问题汇总
    从关系型数据库到非关系型数据库
    SpringMVC学习系列(3) 之 URL请求到Action的映射规则
    Spring MVC的实现原理
    谈谈对Spring IOC的理解
    hash算法 (hashmap 实现原理)
    为什么不能用两次握手进行连接?
    JVM内存管理和JVM垃圾回收机制
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/13638951.html
Copyright © 2011-2022 走看看