I have a P2P.network of nodes holding records of key:value, which can pass requests to other nodes on the.network when the asked node doesn't hold the desired key. The operation always returns an "OK" or an "ERROR". However, when a server thread recieving the request passes it down to all the other connected nodes by calling a method, the anwser ("OK" or "ERROR") isn't captured by the method, but by the main loop in run(). Here is the simplified code: the run() method of the server thread class:
public void run(){
String line;
try {
while (true){
line=in.readLine();
if(line!=null){
else{
switch (line.split(" ")[0]){
case "set-value":
out.println(setValue(line.split(" ")[1]));
break;
System.out.println("default:");
System.out.println(line);
break;
}
}
}
}
} catch (IOException e) {
System.out.println("connection closed with: "+socket.getInetAddress().getHostAddress()+":"+socket.getPort()+" (server socket)");
}
}
the setvalue() method:
private String setValue(String arg) throws IOException {
String setKey = arg.split(":")[0];
String setValue = arg.split(":")[1];
if(DatabaseNode.getKey().equals(setKey)){
DatabaseNode.setValue(setValue);
System.out.println("set-value successful, current record: "+DatabaseNode.getKey()+":"+DatabaseNode.getValue());
return "OK";
} else {
System.out.println("key not on this node, searching...");
for (ServerConnect sc : DatabaseNode.getConnectToClient()) {
System.out.println("sending set-value to: "+sc);
if(sc.sendRead("set-value "+arg ).equals("OK")) {
return "OK";
}
}
for (ServerThread st : DatabaseNode.getConnectedToServer()) {
if(st != this) {
System.out.println("sending set-value to: "+st);
if(st.sendRead("set-value "+arg).equals("OK")) {
return "OK";
}
}
}
}
return "ERROR";
}
and the problematic one, sendRead(), which is supposed to send a string and wait for the anwser, but instead is ignored and anwser is captured by the main run() method
public String sendRead(String str) throws IOException {
out.println(str);
String line;
System.out.println("sent "+str+" awaiting response...");
line = in.readLine();
System.out.println("got "+line);
return line;
}
Thank you for your help
I tried identifying the threads on incoming line, and I am absolutely sure that the same thread which is supposed to read from method just starts a new loop and does nothing with sendRead(). The socket is NOT static, autoFlush on BufferedReader is enabled.
I just figured out what was wrong, the readLine() call in run() steals the next line, leaving the method hanging.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.