简体   繁体   中英

How do I optimize this socket code in java?

I'm developing an application that can control mouse from android phone. The problem is communication is very slow with socket mouse lags while moving. I want to move mouse pointer as the user moves his finger on screen. How can I optimize this code?

On computer side I'm using this code

   try {
                    serverSocket = new ServerSocket(4444);    
            } catch (IOException e) {
                System.out.println("Could not listen on port: 4444");
            }

            System.out.println("Server started. Listening to the port 4444");


        while (true) {
            try {

                clientSocket = serverSocket.accept(); 

                inputStreamReader = new InputStreamReader(
                        clientSocket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader);

                message = bufferedReader.readLine();

                System.out.println(message);
                Robot robot = new Robot();

                switch (message) {

                case "first":
                    ix = MouseInfo.getPointerInfo().getLocation().x;
                    iy = MouseInfo.getPointerInfo().getLocation().y;
                    break;

                case "lclickp":
                    robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
                    break;

                case "lclickr":
                    robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
                    break;


                //several more cases

            } catch (IOException | AWTException ex) {
                System.out.println("Problem in message reading");
            }

and I'm using this on android side.

private class SendMessage extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {

                client = new Socket(Login.IP, 4444); // connect to the server
                printwriter = new PrintWriter(client.getOutputStream(), true);
                printwriter.write(messsage); // write the message to output stream

                printwriter.flush();
                printwriter.close();
                client.close(); // closing the connection

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }


    }

Don't create a new connection per message: keep the socket open. At the server end, process multiple messages per accepted socket, until readLine() returns null.

Now I just beginning learning and I'm not good in socket programming but I think the server should wait for new connections in a separate thread because the ServerSocket.accept() method blocks until there is a connection and causes my app frozen at that line.

Thread conWaitingThread = new Thread(new Runnable(){
while (true){
//try
socket = serverSocket.accept();
//catch
}
void startWaiting(){
comWaitingThread.start();
}

void endWaiting(){
if(conWaitingThread.isAlive()){
conWaitingThread.interrupt();
}
}

and for reading msg from client,

while(input.readLine()!=null){
try{
message = input.readLine();
//ur switch case
}catch (ioException e){
//do catch
}
}

For client side, create socket and iostreams once and let them open. Not close the iostreams as closing iostreams closes the respective socket too. May open socket and io in onCreate and close in onDestroy. Be aware that input.readLine() on serverSide waits the new line char and printWriter.write() does not automatically add that. So you may not get any incoming data although printWriter.flush() is called and you need to concat "\\n" on writing.

On the PC Side of things: Consider refactoring into a few helper classes, perhaps, one for Connect, one for sending updates, and one for Disconnect. Then, you will only need to connect and disconnect once per session.

It's good practice to set a tick rate on both the server and client to prevent over-using CPU time and other resources. There is no need to update mouse coordinates more frequently than the refresh rate of typical monitor can update (60fps / 16.6ms) for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM