将多个 Flex 客户端连接到单个 Java 类
我有一个多用户应用程序,由 Flex 客户端和 blazeds/Spring/java 后端组成 - 我的主要元素工作正常,即。将消息发送到目的地、消费和生产。 Flex 客户端能够从此类发送和检索字符串,没有问题。我想做的是让 2 个客户端能够访问相同的变量。在这个粗略的示例中,我从每个 swf 发送一个 guid,并将其附加到字符串 _players 服务器端。发生的情况是,当我启动 Swf A 时,它会很好地收到其 guid,Swf B 也是如此。然后 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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的班级中存在线程问题。不确定这是否是您问题的原因 - 但有可能。
看来您正在通过
_player
变量共享数据。但这个变量不是线程安全的。它有两个主要问题:要解决这个问题,你必须做两件事:
_players += name + ",";
包装在同步块中(对于问题 1)_players
标记为易失性
(针对问题2)@see http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html
You have a threading problem in you class. It is not sure if this is the cause of your problem - but it could.
It seams that you are sharing data though the
_player
variable. But this variable is not thread safe. It has two major problem:To fix it you have to do two things:
_players += name + ",";
in an synchronized block (for issue 1)_players
asvolatile
(for issue 2)@see http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html
可能是服务器阻止了这种情况。传统上,要在客户端之间共享或以其他方式保留的数据被写入数据库或其他数据源。您可能会很好地使用内存数据库。大多数 Web 服务器都使用 HSQLDB 或 德比.
It's probably the server that's preventing this. Traditionally, data that is to be shared between clients, or otherwise persisted, is written to a DB or some other datasource. You might do well with a in memory DB. Most web servers have one configured out of the box using HSQLDB or Derby.
一般的其他解决方案是使用线程保存集合而不是字符串,但这会导致其他问题,并且不像字符串那么有效。
但无论如何,您应该重新考虑您的决定:在 Thread 类中使用静态变量来存储共享业务数据,例如您的玩家列表。
A general other solution would be using a thread save collection instead of the String, but this my lead to other problems and is not so efficent like your string.
But nevertheless you should rething your decision: to use a static variable in a Thread class to store shared business data like your player list.