2

In Java with ServerSocket and Socket I can transfer image file using the below code in a Local Network:

Send

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();
    }
}

Receive

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();
    }

}

How can I do it in Netty using Socket?

My Handler

@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
            */

        }


    }

I keep on searching for any example of this in Netty and I only found the example with Sending via Http but still I don't know how to do it. By the way, I'm using ObjectEncoder() and ObjectDecoder(ClassResolvers.cacheDisabled(null)) in my Pipeline.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Polar
  • 3,327
  • 4
  • 42
  • 77

2 Answers2

0

Solving my problem:

sending

  1. Get the file
  2. Convert to byte array
  3. Send

Receive

  1. Get the receive byte array
  2. Convert back to image
  3. Save

My Handler

@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());
            }

        }


    }

I'm not sure if how others actually do this on Netty but this how I solved it.

NOTE: you might have issue while transferring large file using this solution.

Polar
  • 3,327
  • 4
  • 42
  • 77
0

Your approach is fine but you might have issue while transferring large file in general (not only limited to image file). I would recommend you to take a look at ChuckedWriteHandler in here, the documentation is well-written to follow.

sayboras
  • 4,897
  • 2
  • 22
  • 40
  • Exactly, I'm facing it right now, thanks! I will check the linkm – Polar Dec 13 '17 at 02:44
  • I'm having trouble using the `ChuckedWriteHandler`, I need to send it as ArrayList containing the image and text on it... – Polar Dec 13 '17 at 10:34
  • Hi! I've been having a trouble using `ChunckedWriteHandler`, can you please have your time looking for my followup question https://stackoverflow.com/questions/47792126/sending-large-object-containing-string-and-image-file Thanks! – Polar Dec 13 '17 at 12:35
  • just saw your comment, and in another follow-up question https://stackoverflow.com/questions/47794599/how-to-chunk-listobject-in-netty, there was already a bunch of good suggestions. So by now, I think you already figure it out – sayboras Dec 15 '17 at 02:04
  • I actually I'm having a hard time figuring the problem. . . from the followup question, @St.Antario suggested a method that chunks the `List` but I still having the problem of large file just like what you said, until I'm still trying to figure the problem . . . :-( – Polar Dec 15 '17 at 10:25
  • I give up. . . I'm having a hard time understanding this library. . . :( I now using `ServerSocket` and `Socket` from my old project. Thank you. – Polar Dec 15 '17 at 16:00