Java thread to run keystrokes where the cursor is blinking through socket programming

Hi guys,

Today we learn a great program where we do a java thread to run keystrokes where the cursor is blinking through socket programming. Suppose cursor is blinking somewhere. now you want to append or write some text which will be from an external source like Laser scanner, socket or anything else. Let’s do the job. First of all, create a java class named RunningThread

import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class RunningThread extends Thread{
    private boolean tRun;
    private Socket sock;
    private String ip, port;
    private Robot robot;
    RunningThread(boolean trun, String ip, String port, Socket sock) {
        this.tRun=true;
        this.ip=ip;
        this.port=port;
        this.sock=sock;
    }
    private RunningThread(){

    }
    public void run(){
        try {
            sock = new Socket(ip, Integer.parseInt(port));
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (tRun){
            InputStreamReader streamReader= null;
            try {
                streamReader = new InputStreamReader(sock.getInputStream());
                BufferedReader reader= new BufferedReader(streamReader);
                String value =reader.readLine();
                RunningThread runningThread=new RunningThread();
                runningThread.type(value.concat("\n"));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void type(String s) throws AWTException {
        robot = new Robot();
        byte[] bytes = s.getBytes();
        for (byte b : bytes) {
            int code = b;
            // keycode only handles [A-Z] (which is ASCII decimal [65-90])
            if (code > 96 && code < 123) {
                code = code - 32;
            }
//            robot.delay(40);
            robot.keyPress(code);
            robot.keyRelease(code);
        }
    }
}

Now we need to call the thread from our main function with the constructor’s parameter.

Socket sock= null;
public static void main(String[] args) {
    rThread=new RunningThread(true, "127.0.0.1", "81", sock);
    rThread.start();
}

Here our system will work as a TCP client. So it will communicate with the server and wait for a message from the server.

Tags:
92 Views

About Author

Nasir

Welcome to CodeKit.xyz. I am working in an automation company as a software engineer. From the deep thirst of learning, I have developed this platform.