我有一个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
忘记代码,你想具体实现什么? –