2012-04-11 64 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如果另一端关闭套接字。当套接字处于活动状态时,该呼叫将阻塞,直到有更多数据可用。

你需要做的是改变你的“协议”:客户端应该首先发送数组大小,然后发送数据。服务器应该读取该长度,并在完成后停止读取文件(回到等待下一个文件)。

相关问题