我可以在RESTful Web服务中使用wait()吗?

HAI

我有一个RESTful Web服务,用于NetBeans上的服务器。该Web服务应从客户端(多人游戏)获得许多请求。

我仍然是这个主题的新手,但如果我理解正确的话-客户端到我的Web服务的每个调用都是线程安全的-因为与Web服务的每个连接都在不同的线程上(我的所有变量都在webservice方法内部)是这是真的?

这使我wait();想到了一个问题:我可以在Webservice方法内使用吗?假设我正在等待两个客户端连接,因此第二个连接将使用。notifyAll();但是由于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();
} } }`
特德·特里平

您可以始终使用wait()notify()因为它会影响正在其上运行代码的线程。是否应使用它取决于情况。

如果您要排队,请使用队列:)

一个小例子,我敲了...

@Path("/w")
public class JSONRESTService {

    private static BlockingQueue<Player> queue = new ArrayBlockingQueue<>(999);

    @POST
    @Consumes("application/json")
    @Path("/JSONService")
    public String JSONREST(InputStream incomingData) {    


        Player thisPlayer = ...; // Get player from session or something

        System.out.println (thisPlayer.getName() + " starting...");

        try {

            if (queue.isEmpty()) {
                System.out.println ("waiting for an opponent");
                queue.add(thisPlayer);
                synchronized (thisPlayer) {
                    thisPlayer.wait();
                }
            } else {
                System.out.println ("get next in queue");
                Player opponent = queue.take();
                opponent.setOpponent(thisPlayer);
                thisPlayer.setOpponent(opponent);
                synchronized (opponent) {
                    opponent.notify();
                }
            }

            System.out.println (thisPlayer.getName() + " playing " + thisPlayer.getOpponent().getName());

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    static class Player {

        private String name;
        private Player opponent;

        Player (String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public Player getOpponent() {
            return opponent;
        }

        public void setOpponent(Player opponent) {
            this.opponent = opponent;
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我可以编写两个类似的Restful Web服务吗

我们可以在单个intentservice的onHandleIntent()中使用多个Web服务调用吗?

我可以在服务中使用SQL查询吗

我们可以在服务中使用PDFRenderer吗?

Swift - 我可以在通知服务扩展中使用领域吗?

在RESTful Web服务中使用多个资源

我可以在 Web 程序集中使用 DataGrid 吗?

可以在服务中使用 LiveData 对象吗?

如何在我的JSF项目中使用RESTful Web服务?

我可以在不同业务的域服务中使用通用服务吗?

我可以在生产服务器中使用flowplayer吗?它是免费的吗?

我们可以使Restful Webservice成为有状态的吗

URI 包含 HTTP 动作动词。我可以考虑这个 API RESTful 吗?

即使我的网站使用SSL服务,我也可以强制Web套接字不使用SSL吗?

我可以使用Firebase Hosting在Node.js中编写RESTful API

我可以在不依赖 Elastic Search 的 npm 的情况下使用 Elastic Search RESTful API

我可以在HTML中使用变量吗?

我可以在匹配中使用“ <”和“>”吗?

我可以在AnyObject中使用元组吗?

我可以在PureComponent中使用shouldComponentUpdate吗

我可以在查询中使用Mutators吗?

我可以在JTA中使用Hibernate吗?

我可以在DrawerLayout中使用SwipeRefreshLayout吗?

我可以在ARC中使用retain吗?

我可以在 <urlset> 中使用 <sitemap> 吗?

我可以在渲染中使用引用吗?

我可以在PowerShell中使用“ &&”或“ -and”吗?

我可以在cgo中使用c ++吗?

我可以在UIScrollView中使用UIRefreshControl吗?