2012-04-11 3 views
0

바이트 배열을 보내는 전화에서 연결을 허용하는 프로그램이 있는데, 연결이 만들어 졌을 때 테스트 할 수 있지만 어떻게 실제로 수신하고 있는지 어떻게 알 수 있습니까? 어떤 것이 소켓을 통해 전송되는지 어떻게 알 수 있습니까? 왜냐하면 아래 코드에서 "saved.jpg"파일을 생성 할 수 없기 때문입니다. 이것은 아무것도받지 못했다는 의미입니까? 다른 쪽 끝은 소켓을 닫으면소켓을 통해 바이트 배열 수신

public class wpsServer { 

    //vars 
    private int svrPort = 3334; 
    private ServerSocket serverSocket; 
    private Image image = null; 

    public wpsServer() 
    { 
     try { 
      serverSocket = new ServerSocket(svrPort); 
      System.out.println("Server started on "+svrPort); 
     } 
     catch (IOException e) { 
      System.out.println("Could not listen on port: "+svrPort); 
      System.exit(-1); 
     } 
    } 

    public void listenForClient() 
    { 
     Socket clientSocket = null; 
     try { 
      clientSocket = serverSocket.accept(); 
      if(clientSocket.isConnected()) 
       System.out.println("Connected"); 

      byte[] pic = getPicture(clientSocket.getInputStream()); 
      InputStream in = new ByteArrayInputStream(pic); 
      BufferedImage image = ImageIO.read(in); 
      File outputfile = new File("saved.jpg"); 
      ImageIO.write(image, "jpg", outputfile); 

     } 
     catch (IOException e) { 

      System.out.println("Accept failed: "+svrPort); 
      System.exit(-1); 
     } 

    } 

    public byte[] getPicture(InputStream in) { 
      try { 
      ByteArrayOutputStream out = new ByteArrayOutputStream(); 
      byte[] data = new byte[1024]; 
      int length = 0; 
      while ((length = in.read(data))!=-1) { 
       out.write(data,0,length); 
      } 
       return out.toByteArray(); 
      } catch(IOException ioe) { 
      //handle it 
      } 
      return null; 
     } 

} 

답변

0

in.read 전화는 -1를 반환합니다. 소켓이 살아있는 동안에는 더 많은 데이터를 사용할 수있을 때까지 해당 호출이 차단됩니다.

"프로토콜"을 변경해야합니다. 먼저 클라이언트가 배열 크기를 보낸 다음 데이터를 보내야합니다. 서버는 그 길이를 읽어야하며, 파일이 끝나면 파일 읽기를 중단해야합니다 (예를 들어 다음 파일을 기다리는 것으로 돌아갑니다).

관련 문제