繁体   English   中英

使用套接字发送和接收图像

[英]Sending and Receiving image using Socket

在带有ServerSocketSocket Java中,我可以在本地网络中使用以下代码传输图像文件:

发送

public class Send {

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket(serverIP, serverPORT);
        OutputStream outputStream = socket.getOutputStream();

        BufferedImage image = ImageIO.read(new File("test.jpg"));

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", byteArrayOutputStream);

        byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
        outputStream.write(size);
        outputStream.write(byteArrayOutputStream.toByteArray());
        outputStream.flush();

        socket.close();
    }
}

接收

public class Receive {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(serverPORT);
        Socket socket = serverSocket.accept();
        InputStream inputStream = socket.getInputStream();

        byte[] sizeAr = new byte[4];
        inputStream.read(sizeAr);
        int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();

        byte[] imageAr = new byte[size];
        inputStream.read(imageAr);

        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));

        ImageIO.write(image, "jpg", new File("test2.jpg"));

        serverSocket.close();
    }

}

我该如何在Netty使用Socket?

我的经理

@Override
    protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
        Channel currentChannel = ctx.channel();
        System.out.println(TAG + "MESSAGE FROM SERVER - " + currentChannel.remoteAddress() + " - " + o);

        List<Object> msg = new ArrayList<>();
        msg.addAll((Collection<? extends Object>) o);

        /*If message in index 0 is Equal to IMAGE then I need to send an Image File*/
        if(msg.get(0).equals("IMAGE")){

            /*
                NO IDEA on how can I send it on Netty.
                I'm not sure if this will work or this is how should I do it.
            */

                BufferedImage image = ImageIO.read(new File("test.jpg"));
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, "jpg", byteArrayOutputStream);
                byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();

                msg.clear(); //clear the List Object
                msg.add(0, "IMAGE_FILE"); //Add the Type of message with String
                msg.add(1, size); //Add the size
                msg.add(2, byteArrayOutputStream.toByteArray()); //Add the image file to send 
                sendMessage(ctx, msg);

            ctx.writeAndFlush(msg); //Finally Send it.
        }

        /*If message in index 0 is Equal to IMAGE_FILE then I need to make it viewable*/
        if(msg.get(0).equals("IMAGE_FILE")){

            /*
                NO IDEA on how to decode it as an Image file
            */

        }


    }

我继续在Netty中搜索任何此类示例,但仅通过“通过Http发送”找到了示例,但我仍然不知道该怎么做。 顺便说一句,我在我的管道中使用ObjectEncoder()ObjectDecoder(ClassResolvers.cacheDisabled(null))

解决我的问题:

发送

  1. 获取文件
  2. 转换为字节数组
  3. 发送

接收

  1. 获取接收字节数组
  2. 转换回图片

我的经理

@Override
    protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
        Channel currentChannel = ctx.channel();
        System.out.println(TAG + "MESSAGE FROM SERVER - " + currentChannel.remoteAddress() + " - " + o);

        List<Object> msg = new ArrayList<>();
        msg.addAll((Collection<? extends Object>) o);

        /*If message in index 0 is Equal to IMAGE then I need to send an Image File*/
        if(msg.get(0).equals("IMAGE")){

            byte[] imageInByte;
            BufferedImage originalImage = ImageIO.read(new File("test.jpg"));

            // convert BufferedImage to byte array
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(originalImage, "jpg", baos);
            baos.flush();
            imageInByte = baos.toByteArray();
            baos.close();

            msg.clear(); //clear the List Object
            msg.add(0, "IMAGE_FILE"); //Add the Type of message with String
            msg.add(1, imageInByte); //Add the Converted image in byte
            ctx.writeAndFlush(msg); //Finally Send it.
        }

        /*If message in index 0 is Equal to IMAGE_FILE then I need to get and Save it to use later*/
        if(msg.get(0).equals("IMAGE_FILE")){

            try {

                byte[] imageInByte = (byte[]) msg.get(1); //Get the recieve byte
                // convert byte array back to BufferedImage
                InputStream in = new ByteArrayInputStream(imageInByte);
                BufferedImage bImageFromConvert = ImageIO.read(in);

                ImageIO.write(bImageFromConvert, "jpg", new File("test.jpg")); //Save the file

            } catch (IOException e) {
                System.out.println(e.getMessage());
            }

        }


    }

我不确定其他人实际上如何在Netty上执行此操作,但是我如何解决它。

注意:使用此解决方案传输大文件时,您可能会遇到问题。

您的方法很好,但通常在传输大文件时可能会遇到问题(不仅限于图像文件)。 我建议您在这里看看ChuckedWriteHandler ,该文档编写得井井有条。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM