I have a server connected to two clients, and I want to send messages from one to another with only one client active at a time, so after every message send it waits for response from the other client. Therefore client should know if the first thing it needs to do is write a message to 2nd client or wait for a message from 1st one.
This is the server side of my project:
public void connect() throws IOException { log(TA, "ServerSocket created. \nListering for connections...\n"); server = new ServerSocket(port, 2); conn1 = server.accept(); output1 = new PrintWriter(conn1.getOutputStream()); input1 = new BufferedReader(new InputStreamReader( conn1.getInputStream())); log(TA, "User " + 1 + " connected.\n"); output1.println("1"); conn2 = server.accept(); output2 = new PrintWriter(conn2.getOutputStream()); input2 = new BufferedReader(new InputStreamReader( conn2.getInputStream())); log(TA, "User " + 2 + " connected.\n"); output2.println("2"); while (true) { String text = input1.readLine(); TA.append("Player 1: " + text + "\n"); output2.println("Player 1: " + text); text = input2.readLine(); TA.append("Player 2: " + text + "\n"); output1.println("Player 2: " + text); } }
And this is the client:
private static void connect() throws IOException { conn = new Socket("192.168.0.25", port); TA.append("Socket created.\n"); out = new PrintWriter(conn.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); TA.append("Streams created.\n"); String inputLine; while ((inputLine = in.readLine()) != null) player_number = Integer.parseInt(inputLine); TA.append("Your ID is " + player_number + " ."); } public void actionPerformed(ActionEvent evt) { String text = TF.getText(); TA.append("Me: " + text + "\n"); TF.selectAll(); TA.setCaretPosition(TA.getDocument().getLength()); if (player_number == 2) try { TA.append("Player 1: " + in.readLine()); } catch (IOException e1) { e1.printStackTrace(); } out.println(text); if (player_number == 1) try { TA.append("Player 2: " + in.readLine()); } catch (IOException e1) { e1.printStackTrace(); } }
What it should do is as soon as connection to one client is made, server should let it know if its 1st or 2nd one, and client should "aknowledge" it by writing `"Your ID is " + player_number + " ."`. This should happen before I enter anything to either textfields. But what happens now, I start the server and both clients, only get to `"Streams created"` message on clients and when I send something from 1st client it shows in server's textarea, but not in the other client. The client I send the message from just freezes.
This is somehow related to the `parseInt` part because that's where the program stops, but i don't know why.