title: How to send image through TCP socket in java
body: <p>friends! 
  I want to get remote PCs screen in my PC! I have tried to write in UDP and now I'm tring to write it in TCP protocol, but there some problems! IF somebody could show me what is the problem I'll appreciated... And here is my code: 
  Server.java</p>
  
  <pre><code>public Server(int port){
      this.G_PORT = port;
  }
  void sendMessage() throws IOException, AWTException{
      servSocket = new ServerSocket(G_PORT);
      System.out.println("Waiting...");
      cSocket = servSocket.accept();
      System.out.println("Server has connected to " + cSocket.getRemoteSocketAddress() + " on " + cSocket.getPort() +" port");
  
          BufferedOutputStream buffOS = new BufferedOutputStream(cSocket.getOutputStream());
          Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
          Rectangle r = new Rectangle(d);
  
          KeyStroke keyStr = KeyStroke.getKeyStroke("ESCAPE");
  
          FileInputStream fileIN = null;
          OutputStream out = null;
  
      //while(keyStr.getKeyCode() != 27){
          bot = new Robot();
          buffIMG = bot.createScreenCapture(r);
          ImageIO.write(buffIMG, "jpeg", new File("D:\\ScreenShots\\test.jpeg"));
          fileIN = new FileInputStream(new File("D:\\ScreenShots\\test.jpeg"));
          out = cSocket.getOutputStream();
          int read, readTotal = 0;
          byteToIMG = new byte[BUFF_SIZE];
  
          while((read =  fileIN.read())!= -1){
              out.write(byteToIMG,0,read);
              System.out.println("IMG sended");
          }
      //}
      out.close();
      fileIN.close();
      cSocket.close();        
  } 
  </code></pre>
  
  <p>and Client.java</p>
  
  <pre><code>void recievMessage(long starTime) throws UnknownHostException, IOException{
      cSocket = new Socket(InetAddress.getByName(G_HOST), G_PORT);
      System.out.println("Connected");
      JFrame frame = new JFrame("My frame");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
      JLabel label = new JLabel();
      ImageIcon icon;
  
      InputStream in = cSocket.getInputStream();
      byteToIMG = new byte[BYTE_SIZE];
      int read;
      int readTotal = 0;
          while((read = in.read(byteToIMG)) != -1){
              readTotal += read;
              InputStream imgIN = new ByteArrayInputStream(byteToIMG);
              buffIMG = ImageIO.read(imgIN);
              icon = new ImageIcon();
              icon.setImage(buffIMG);
              label.setIcon(icon);
              frame.getContentPane().add(label, BorderLayout.CENTER);
              frame.pack();
              System.out.println("IMG recieved");
          }
  } 
  </code></pre>
  
  <p>Please help to solve this problem! If you have another solution suggest! Thanks!</p>