D
D
DimOFF2016-06-23 11:14:14
Java
DimOFF, 2016-06-23 11:14:14

Java. How to correctly organize the interaction with the network?

I do one project as a hobby. In the process of writing the network part, a question arose. The point is the following. My Java application must connect to the server and wait for data from there or transfer it there (a command comes from the server to do something or an event occurs on the client that needs to be reported).
Implemented like this

InputStreamReader isr = new InputStreamReader(client.getInputStream());
            BufferedReader in = new BufferedReader(isr);
            PrintWriter out = new PrintWriter(client.getOutputStream());
            String line;
            String msg;
            while (true) {
                if (isr.ready()) {
                    line = in.readLine();
                    if (line.startsWith("EXIT")) {
                        Logger.getLogger(Client.class.getName()).log(Level.INFO,"Exit");
                        break;                        
                    }
                    if (line.startsWith("BEGIN")) {
                        Logger.getLogger(Client.class.getName()).log(Level.INFO,"BEGIN");
                        break;                        
                    }
                } else {
                    try {
                        this.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (! msg.isEmpty()) {
                    out.println(msg);
                }
            }
            out.close();
            in.close();
            client.close();

Is it possible to do without this.sleep(1);and not heat the air at idle?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Cheremisin, 2016-06-23
@leahch

One way or another, it's better to use NIO, and check for the presence of data through a selector! Here to read - www.javaportal.ru/java/articles/useselectfast.html... (waiting for incoming data)
And refuse to sleep at all - it's not very nice.
Yes, the data may have to be buffered, since it can come in two packages, for example "BEG" and "IN"
Files are another story - this will probably help! The mechanism is similar - https://docs.oracle.com/javase/tutorial/essential/...

F
Fat Lorrie, 2016-06-23
@Free_ze

One way or another, you will have to check for the presence of data (this may be hidden behind the asynchronous call mechanism, but the essence will be the same - eventloop). By duration sleep, you can look for a balance between the response speed and the resources occupied.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question