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/ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。
  • 相关阅读:
    .NET Interop 工具集
    关于正弦波的算法
    Windows Phone 系列 本地数据存储
    Xaml cannot create an instance of “X”
    Windows Phone 系列 使用 MVVM绑定时无法获取当前值
    Windows Phone 系列 应用程序图标无法显示
    Windows Phone 系列 WPConnect无法上网的问题
    Windows Phone 系列 使用 Windows Phone 保存铃声任务
    WP7.5提交应用
    Windows Phone 系列 动态删除ObservableCollection
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/13638951.html
Copyright © 2011-2022 走看看