Skip to content

Instantly share code, notes, and snippets.

@LeRoiDesKiwis
Last active April 25, 2019 17:09
Show Gist options
  • Save LeRoiDesKiwis/dbce43ea9946730138fc581463b5830a to your computer and use it in GitHub Desktop.
Save LeRoiDesKiwis/dbce43ea9946730138fc581463b5830a to your computer and use it in GitHub Desktop.
package fr.leroideskiwis.client;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Scanner;
import java.util.function.Consumer;
public class Main {
private Scanner scan;
private final int port = 2368;
public Main() throws Exception {
this.scan = new Scanner(System.in);
String ip = readString("Adresse ip : ");
Socket socket = tryConnect(ip, port, 5);
log("Connected !");
while(true){
try {
waitString(socket, "R");
log("Packet detected ! Processing screenshot...");
BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
write(socket, image.getWidth() + ";" + image.getHeight() + ";" + image.getType());
ByteBuffer buffer = ByteBuffer.allocate(4*image.getHeight()*image.getWidth());
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
buffer.putInt(image.getRGB(x,y));
}
}
socket.getOutputStream().write(buffer.array());
log("Flushing...");
socket.getOutputStream().flush();
log("Screenshot sended ! Waiting for another packet...");
}catch(Exception e){
error("An error was occured while sending or waiting packet... We try to re-connect to the server each 5s.");
socket = tryConnect(ip,port, 5);
}
}
}
public Socket tryConnect(String ip, int port, int seconds){
return tryConnect(ip, port, seconds, () -> error("An error was occured while try to connect to the server... Retrying in "+seconds+"s"));
}
public Socket tryConnect(String ip, int port, int seconds, Runnable error){
Socket socket = null;
while(socket == null){
try {
socket = new Socket(ip, port);
Thread.sleep(seconds * 1000);
}catch(Exception e){
error.run();
}
}
return socket;
}
public void error(String s){
System.out.println("[ERROR] "+s);
}
public void waitPacket(Socket socket, int number) throws IOException, InterruptedException {
while(socket.getInputStream().read() == -1){
Thread.sleep(1);
}
}
public void waitString(Socket socket, String string) throws IOException, InterruptedException {
while(!readString(socket).equals(string)){
Thread.sleep(1);
}
}
public void write(Socket socket, String write) throws IOException {
socket.getOutputStream().write(write.getBytes());
socket.getOutputStream().write('\t');
socket.getOutputStream().flush();
}
public void log(String s){
System.out.println("[LOG] "+s);
}
public static void main(String... args) throws Exception {
new Main();
}
public int read(Socket socket) throws IOException, InterruptedException {
while(socket.getInputStream().available() <= 0){
Thread.sleep(500);
}
return socket.getInputStream().read();
}
public String readString(Socket socket) throws IOException {
StringBuilder builder = new StringBuilder();
int read = socket.getInputStream().read();
while(read != '\t'){
builder.append((char)read);
read = socket.getInputStream().read();
}
return builder.toString();
}
public String readString(String s){
System.out.print(s);
String read = scan.nextLine();
System.out.println();
return read;
}
}
package fr.leroideskiwis.client;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class Main {
private List<Socket> sockets = new ArrayList<>();
private ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
private Scanner scan = new Scanner(System.in);
public Main() throws Exception {
ServerSocket server = new ServerSocket(2368);
submit(() -> {
while (true) {
try {
Socket socket = server.accept();
log("A guy with ip " + socket.getInetAddress().getHostAddress() + " is connected.");
Optional<Socket> doubleSocket = sockets.stream().filter(s -> s.getInetAddress().getHostAddress().equals(socket.getInetAddress().getHostAddress())).findAny();
if(doubleSocket.isPresent()){
log("Double is detected ! Removing the first...");
sockets.remove(doubleSocket.get());
log("Removed !");
}
sockets.add(socket);
} catch (Exception e) {
error("Error while trying to connect a client.");
}
}
}, "accept-thread");
submit(() -> {
while(true){
sleep(1);
sockets.stream().filter(s -> !s.isConnected()).forEach(s -> {
sockets.remove(s);
log("The socket "+s.getInetAddress().getHostAddress()+" has been removed because of disconnect");
});
}
}, "deleter-thread");
submit(() -> {
while (true) {
String ip = readString("Adresse ip : ");
Optional<Socket> optional = sockets.stream().filter(s -> s.getInetAddress().getHostAddress().equals(ip)).findAny();
if (!optional.isPresent()) {
error(ip + " was don't found");
continue;
}
Socket socket = optional.get();
log("Processing... Please wait.");
try {
processScreenshot(socket);
} catch (Exception exception) {
exception.printStackTrace();
error("Error while processing screenshot... Cancelling.");
}
}
}, "receiving-thread");
}
public void sleep(int time){
sleep(time, () -> error("An error has occured while sleep the thread"+Thread.currentThread().getName()));
}
public void sleep(int time, Runnable runnable){
try{
Thread.sleep(time);
}catch(Exception exception){
runnable.run();
}
}
public void processScreenshot(Socket socket) throws Exception {
write(socket, "R");
String[] args = readString(socket).split(";");
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
int type = Integer.parseInt(args[2]);
BufferedImage image = new BufferedImage(width, height, type);
log("Image with dimentions " + width + "x" + height + " will be downloading...");
byte[] buffer = new byte[4096];
ByteBuffer readBuffer = ByteBuffer.allocate(width * height * 4);
while (readBuffer.remaining() > 0) {
int length = Math.min(4096, readBuffer.remaining());
read(socket, buffer, length);
System.out.println("Reading: " + length + " bytes, remaining: " + readBuffer.remaining());
readBuffer.put(buffer, 0, length);
}
log("Data readed ! Parsing...");
readBuffer.rewind();
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
int value = readBuffer.getInt();
image.setRGB(x, y, value);
}
}
image.flush();
File dest = getFile("./screenshots/", socket.getInetAddress().getHostAddress(), "png");
ImageIO.write(image, "png", dest);
log("Screenshot writed in " + dest.getAbsolutePath() + " successfully.");
}
public File getFile(String folderPath, String fileName, String extension) throws Exception {
File folder = new File(folderPath);
if (!folder.exists() && !folder.mkdir()) throw new Exception("Can't create folder.");
File file = new File(folderPath + fileName + "." + extension);
if (!file.exists()) return file;
for (int i = 0; ; i++) {
file = new File(folderPath + fileName + i + "." + extension);
if (!file.exists()) break;
}
return file;
}
public String readString(String s) {
System.out.print(s);
String read = scan.nextLine();
System.out.println();
return read;
}
public void submit(Runnable runnable, String name) {
executor.setThreadFactory(r -> {
Thread th = new Thread(runnable);
th.setName(name);
return th;
});
executor.submit(runnable);
}
public void read(Socket socket, byte[] bytes, int length) throws IOException {
while(socket.getInputStream().available() < length);
socket.getInputStream().read(bytes);
}
public String readString(Socket socket) throws IOException {
StringBuilder builder = new StringBuilder();
int read = socket.getInputStream().read();
while (read != '\t') {
builder.append((char) read);
read = socket.getInputStream().read();
}
return builder.toString();
}
public void write(Socket socket, int write) {
try {
byte[] bytes = ByteBuffer.allocate(4).putInt(write).array();
socket.getOutputStream().write(bytes);
socket.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(Socket socket, String write) throws IOException {
socket.getOutputStream().write(write.getBytes());
socket.getOutputStream().write('\t');
socket.getOutputStream().flush();
}
public static void main(String... args) throws Exception {
new Main();
}
public void error(String s) {
System.out.println("[ERROR] " + s);
}
public void log(String s) {
System.out.println("[LOG] " + s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment