2017-12-12 25 views
0

를 사용하여 이미지를 수신 :보내기 내가 로컬 네트워크에 아래의 코드를 사용하여 이미지 파일을 전송할 수 있습니다 <code>ServerSocket</code> 및 <code>Socket</code> 자바에서 소켓

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에서 Soc를 사용하면 어떻게됩니까? 케?

내 처리기

@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))을 사용하고 있습니다.

답변

0

접근 방법은 괜찮지 만 대용량 파일을 전송할 때 문제가 발생할 수 있습니다 (이미지 파일에만 국한되지 않음). ChuckedWriteHandlerhere에 두는 것이 좋을 것입니다. 문서는 잘 작성되어 있습니다.

+0

바로 지금 당장 직면하고 있습니다. 감사합니다! – Polar

+0

'ChuckedWriteHandler'를 사용하는 데 문제가 있습니다. 이미지와 텍스트가 포함 된 ArrayList로 보내야합니다. – Polar

+0

안녕하세요! 'ChunckedWriteHandler'를 사용하는 데 어려움을 겪어 왔습니다. 내 질문에 대한 답변을 찾고 싶습니다. https://stackoverflow.com/questions/47792126/sending-large-object-containing-string-and-image-file 감사! – Polar

0

내 문제 해결 : 배열

  • 가 수신 보내기

    1. 파일을 바이트
    2. 변환을 얻기 전송을

      다른 사람들이 사실에이 작업을 수행하는 방법 경우
      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하지만이게 내가 어떻게 해결했는지.

      참고 :이 솔루션을 사용하여 큰 파일을 전송하는 중에 문제가 발생할 수 있습니다.