我有一個REST風格的web服務,我使用NetBeans上的服務器。 這個web服務應該從客戶端(多人遊戲)獲得很多請求。我可以在RESTful Web服務中使用wait()嗎?
我仍然對這個主題不熟悉,但如果我理解它是正確的 - 從客戶端到我的webservice的每個調用都是線程安全的 - 因爲與web服務的每個連接都在不同的線程上(所有變量都在webservice方法)是真的嗎?
這使我想到我的問題: 我可以在webservice方法中使用wait();
嗎?假設我正在等待兩個客戶端連接,所以第二個連接將使用notifyAll();
但由於web服務並不是一個真正的線程,我不知道是否有可能在那裏使用這些方法?我應該用什麼來代替?
這是我的web服務:
@Path("/w")
public class JSONRESTService {
String returned;
@POST
@Consumes("application/json")
@Path("/JSONService")
public String JSONREST(InputStream incomingData) {
StringBuilder JSONBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
JSONBuilder.append(line);
}
returned = "transfer was completed";
// This is what I'm trying to add but I know that I can't:
// count is a static variable, every new connection will increase this value
// only one player is connected
if (Utility.count == 1)
wait(); //wait for a 2nd player to connect to this webservice
// 2nd player is connected to this webservice
if (Utility.count == 2)
notifyAll(); // notify the 1st player
} catch (Exception e) {
System.out.println ("Error Parsing: - ");
returned ="error";
}
System.out.println ("Data Received: " + JSONBuilder.toString());
return (returned);
}
}
客戶:
JSONObject jsonObject = new JSONObject("string");
// Step2: Now pass JSON File Data to REST Service
try {
URL url = new URL("http://localhost:8080/w/JSONService");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonObject.toString());
out.close();
//string answer from server:
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
System.out.println("\n"+line);
in.close();
} catch (Exception e) {
System.out.println("\nError while calling JSON REST Service");
System.out.println(e);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
} } }`
多線程之前。 'if(Utility.count = 1)'應該是'if(Utility.count == 1)',第一個分配1來計數。第二點,第二個'if'應該是'else if' –
謝謝!是的,我寫它作爲一個想法,我的問題是web服務中的wait()和notify() – SHAI
忘記代碼,你想具體實現什麼? –