'My program is stuck at readLine and never continues (Java Socket Programming)
I need to create a group of web servers(connected like a list) and each one of them have a list that has every server in it(port,id). When I try to send the list from a server to another, readLine() just gets stuck and never continues. The only time it continues, is when I stop(Ctrl + C) the server that sends the list. I add \n at the end of the output everytime and tried some stuff that I have read online but nothing works.
The bold code is where it gets stuck, I've tested it with System.out.println but it prints nothing, so it gets trapped in the condition I assume.
public class WebServer {
HashMap<String, String> data = new HashMap<String, String>();
public static ArrayList<String> servers = new ArrayList<String>();
public static void main(String[] args) {
int PORT = Integer.parseInt(args[0]);
int id = Integer.parseInt(args[1]);
int connect_port = 0;
String info = args[0] + " " + args[1];
//String info2 = "4356" + " " + "2";
while(true) {
if (id == 1) {
servers.add(info);
// servers.add(info2);
try {
ServerSocket listenSocket = new ServerSocket(4355);
Socket connection = listenSocket.accept();
DataOutputStream outToServer = new DataOutputStream(connection.getOutputStream());
for (String i : servers) { //Sends the server list to the 2nd server
System.out.println(i);
outToServer.writeBytes(i + '\n');
}
} catch (IOException e1) {
}
} else {
// This is every other node, they must be given the list by their previous
// server
try {
if (args[2].equals("connect")) {
Socket socket = new Socket("localhost", 4355);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String i = null;
**while((i = inFromServer.readLine()) != null) {
System.out.println(i);
servers.add(i);
}**
servers.add(info);
socket.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
Thread perdiodic = new Thread(new Periodic(servers,info));
perdiodic.start();
}
}
}
I've tried numerous solutions from other stack overflow questions from other programmers that phased the same thing but nothing worked.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
