Good day, you need to write a simple client and server using sockets in java, but encountered a problem that the program hangs if the client also receives information. It is necessary for me that the client exchanged messages. Tell me how this can be implemented? Thank you in advance.

client public class Main { static ObjectOutputStream out; static ObjectInputStream in; public static void main(String[] args) throws IOException, InterruptedException { Socket socket=new Socket("localhost",4444); in=new ObjectInputStream(socket.getInputStream()); out=new ObjectOutputStream(socket.getOutputStream()); System.out.println("Connected"); write("Test"); String str=read(); System.out.println(str); } public static void write(String str) throws IOException, InterruptedException { out.writeUTF(str); Thread.sleep(1000); out.flush(); } public static String read(){ String str=null; try{ while (true){ str=in.readUTF(); } }catch (IOException ex){} return str; } } server public class Main { static ObjectOutputStream out; static ObjectInputStream in; public static void main(String[] args) throws IOException, InterruptedException { ServerSocket serverSocket=new ServerSocket(4444); Socket socket=serverSocket.accept(); out=new ObjectOutputStream(socket.getOutputStream()); in=new ObjectInputStream(socket.getInputStream()); System.out.println("Connected"); String str=read(); System.out.println(str); write("Test"); } public static void write(String str) throws IOException, InterruptedException { out.writeUTF(str); out.flush(); } public static String read(){ String str=null; try{ while (true){ str=in.readUTF(); } }catch (IOException ex){} return str; } } 
  • because the client has gone into an infinite loop while (true) , which is why he hangs - Senior Pomidor

1 answer 1

because the client has gone into an infinite loop while (true)

the same goes for the server.

Here is an example of a simple cc application.

  • but after all, there will be an exchange of lines in a loop, but I will also need to add logic to the program, how to write a couple of methods to send and receive a string correctly, so that it isn’t messed up. For example, the client sent a string server received a processed-sent response, and then other blocks of code in the client and the server went, and then initialize a similar exchange again? - skiff2011
  • Look carefully at the implementation of the string in the example, it is just expected to complete the stream - Senior Pomidor
  • Understood, thanks - skiff2011