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; } }
while (true), which is why he hangs - Senior Pomidor