There is such a client code:

Socket remoteServer; remoteServer = new Socket("192.168.0.55",4445); BufferedReader in = new BufferedReader(new InputStreamReader(remoteServer.getInputStream())); PrintWriter out = new PrintWriter(remoteServer.getOutputStream(),true); BufferedReader ios = new BufferedReader(new InputStreamReader(System.in)); String fromClient,fromserver; while ((fromClient = ios.readLine())!=null) { out.println(fromClient); //out.write(fromClient); fromserver = in.readLine(); System.out.println(fromserver); if (fromClient.equalsIgnoreCase("close")) break; } out.close(); in.close(); ios.close(); remoteServer.close(); 

That is, it connects to the server and keeps the connection open at the expense of the loop, until a "close" arrives. But here it also keeps due to System.in, as it receives data from the console. But here it is necessary to alter under Android and the problem is that the text should be obtained from editText, and now at this point stuck.

If you do this:

 String fromClient = "Text",fromserver; out.println(fromClient); //out.write(fromClient); fromserver = in.readLine(); System.out.println(fromserver); //if (fromClient.equalsIgnoreCase("close")) break; 

That seems to be how it works, BUT, the connection naturally closes after sending, because there is no loop that would keep the connection open. In general, how to do something, by analogy with the first piece of code, kept open until getting a "close"? Thank.

  • The read / write code for the socket is transferred to a separate thread. - KoVadim
  • Rendered from the beginning. Otherwise it does not work. - Kamenev_D

1 answer 1

When I did a socket connection, I transferred all the work of the socket to the Service , in which the read-write was in a separate thread. I think this is the most suitable option.

  • In AciveSync rendered. The first piece of code works with retention. It's not a thread, but a loop. - Kamenev_D
  • What's wrong with the loop? I started a while loop in a separate thread, which was executed until there was no command to close the connection. - Nikotin N
  • So this is the question. How to make this cycle, by analogy with the first code. Without using System.in - Kamenev_D