Made a simple client server. Did a cycle

while (connected) { try { in = new BufferedReader(new InputStreamReader(fromClient.getInputStream())); System.out.print("Message got: " + in.toString() + "\n"); out = new PrintWriter(fromClient.getOutputStream(), true); System.out.print("Message sent: " + out.toString() + "\n"); } catch (IOException e) { System.out.print("Cannot get input stream from client\n"); } } 

Is this technically correct? Is it possible to make the server execute only if the client sends a message? Or just put Thread.sleep(1000);


And another such question. Do I need to recreate the socket. Or make it a global static variable?

  • one
    I think correctly. that's why he and the server would sit and wait :) - SergeiK
  • The code is shortened so much that I want to say "yes, nonsense." There is no reading and writing to the socket in the code (and reading by calling InputStream.read blocks, so the server only performs if the client turns out by itself), which socket you are going to re-create is also unclear. - zRrr

1 answer 1

Thread.sleep(200) is enough. you have an infinite loop, because connected never changes status. If there is a method checking connection, then let it in a separate thread. but inside realize the status

connected = fromClient.isConnected(); Thread.sleep(200)

  • connected changes status. This I gave the code without the "water". In fact, I generally replaced BufferedReader and PrintWriter with InputStream and OutputStream respectively. And if in the InputStream text is "Exit" then connected = false and the loop ends. Thanks for the answer. I would like to know whether you need to re-create a socket - Herrgott
  • one
    I see no point in re-creating the socket, especially on the server - Senior Pomidor