Java ee7 websockets服务器端点无法正常工作

时间:2015-07-22 19:36:32

标签: java maven websocket

这是我服务器的代码

package local.xx.mavenws;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import javax.enterprise.context.ApplicationScoped;
import org.joda.time.DateTime;

@ApplicationScoped
@ServerEndpoint("/")
public class Server {

    private final ArrayList<Session> sessions;

    public Server() {
        this.sessions = new ArrayList<>();
    }

    @OnOpen
    public void onOpen(Session session) {
        this.sessions.add(session);
        this.echo("Client connected!");
    }

    @OnClose
    public void onClose(Session session) {
        this.sessions.remove(session);
        this.echo("Client disconnected!");
    }

    @OnError
    public void onError(Throwable error) {
        this.echo("Error occured!");
        this.echo(error.getLocalizedMessage());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            message = "[" + this.currentDate() + "] " + message;
            this.echo(message);
            for( Session sess : this.sessions ) {
                sess.getBasicRemote().sendText(message);
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void echo(String info) {
        System.out.println(info);
    }
    private String currentDate() {
        String dateArray[] = (new DateTime()).toString().split("T");
        String date = dateArray[0] + " " + (dateArray[1].split("\\.")[0]);
        return date;
    }
}

我希望它将收到的消息发送给所有连接的用户。问题是,它会单独处理每个连接,就像每个连接都拥有自己的服务器实例一样。当我在两个浏览器窗口中连接时,消息会单独显示。有没有人对此有任何想法?

1 个答案:

答案 0 :(得分:1)

终于搞定了!解决方案是sessions变量必须是静态的,我必须始终在Server范围内调用它,而不是this。这意味着,尽管为每个连接的用户创建了Server的新实例,但该变量对每个人都是相互的。