You can find a (non-compiled) example in easywayprogramming .
I simplified and fixed the errors, I hope this is a useful answer to your question.
Start the server first, and then start the client as often as you want.
In the example, take a screenshot of the upper left 200x100 pixels of your screen, send them to the server, which will open a new window and display a screenshot.
GreetingServer.java
import java.awt.image.BufferedImage; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.sql.SQLException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class GreetingServer extends Thread { private ServerSocket serverSocket; Socket server; public GreetingServer(int port) throws IOException, SQLException, ClassNotFoundException, Exception { serverSocket = new ServerSocket(port); serverSocket.setSoTimeout(180000); } public void run() { while(true) { try { server = serverSocket.accept(); BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream())); JFrame frame = new JFrame(); frame.getContentPane().add(new JLabel(new ImageIcon(img))); frame.pack(); frame.setVisible(true); } catch(SocketTimeoutException st) { System.out.println("Socket timed out!"); break; } catch(IOException e) { e.printStackTrace(); break; } catch(Exception ex) { System.out.println(ex); } } } public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception { Thread t = new GreetingServer(6066); t.start(); } }
GreetingClient.java
import java.awt.AWTException; import java.awt.Image; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.Socket; import javax.imageio.ImageIO; public class GreetingClient { Image newimg; static BufferedImage bimg; byte[] bytes; public static void main(String [] args) { String serverName = "localhost"; int port = 6066; try { Socket client = new Socket(serverName, port); Robot bot; bot = new Robot(); bimg = bot.createScreenCapture(new Rectangle(0, 0, 200, 100)); ImageIO.write(bimg,"JPG",client.getOutputStream()); client.close(); } catch(IOException | AWTException e) { e.printStackTrace(); } } }
source share