将多个Flex客户端连接到单个Java类

时间:2010-12-02 13:27:58

标签: java spring blazeds

我有一个多用户应用程序,包括一个flex客户端和blazeds / Spring / java后端 - 我有主要元素工作正常,即。向目的地发送消息,消费和生产。 Flex客户端能够从此类发送和检索字符串没问题。我想要做的是让2个客户端访问相同的变量..在这个粗略的样本中,我从每个swf发送一个guid,我追加到字符串_players服务器端。当我启动Swf A时,它会像Swf B一样收回它的guid。然后Swf A接收来自Swf B的guid,但是Swf B没有接收到Swf A.顺便说一句,这是刚刚启动两次的swf代码每个在不同的浏览器中。

任何人都可以看到我出错的地方或可能是更好的解决方案吗?

public class GameFeed {

    private static GaneFeedThread thread;

    private final MessageTemplate template;

    public GameFeed(MessageTemplate template) {
        this.template = template;
    }

    public void start() {
        if (thread == null) {
            thread = new GaneFeedThread(this.template);
            thread.start();
        }
    }

    public void stop() {
        thread.running = false;
        thread = null;
    }

    public static class GaneFeedThread extends Thread {

        public boolean running = false;

        private final MessageTemplate template;

        public GaneFeedThread(MessageTemplate template) {
            this.template = template;
        }

        private static String _players;

        public void addPlayer(String name)
        {
            _players += name + ",";
        }
        while (this.running) {


                this.template.send("game-feed", _players);

        }

3 个答案:

答案 0 :(得分:0)

这可能是服务器阻止了这一点。传统上,要在客户端之间共享或以其他方式持久保存的数据被写入DB或某些其他数据源。你可能会在内存数据库中做得很好。大多数网络服务器都使用HSQLDBDerby开箱即用。

答案 1 :(得分:0)

您上课时遇到线程问题。它不确定这是否是你问题的原因 - 但它可以。

通过_player变量,您正在共享数据。但是这个变量不是线程安全的。它有两个主要问题:

  • 问题1:如果两个客户端同时调用addPlayer方法 - 不清楚您的播放器变量会发生什么情况 - 最少可能会有更新丢失的内容
  • 问题2 :(这可能是原因) - Java内存模型不保证在没有适当的并发管理的情况下在两个线程中更新_player变量。

要修复它,你必须做两件事:

  • 首先:将_players += name + ",";包裹在同步块中(针对问题1)
  • 秒:将_players标记为volatile(针对问题2)

@see http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html

答案 2 :(得分:0)

一般的其他解决方案是使用线程保存集合而不是字符串,但这导致了其他问题并且不像字符串那样高效。

但是你应该做出决定:在Thread类中使用静态变量来存储像播放器列表这样的共享业务数据。