简体   繁体   English

Java EE7 Websockets服务器端点不起作用

[英]Java ee7 websockets server endpoint not working

Here's my server's code 这是我服务器的代码

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;
    }
}

I want it to send received message to all the users connected. 我希望它向所有连接的用户发送接收到的消息。 The problem is, it treats every connection individually like each one of them had it's own instance of the server. 问题是,如果每个连接都有自己的服务器实例,则将每个连接单独对待。 When I connect in two browser windows, messages show separately. 当我在两个浏览器窗口中连接时,消息将分别显示。 Does anybody have any ideas on this? 有人对此有任何想法吗?

Finally got this working! 终于成功了! The solution is that the sessions variable must be static and I had to call it always by Server scope, not this . 解决方案是, sessions变量必须是静态的,我必须始终通过Server作用域而不是this来调用它。 That implicates the fact that, despite there's a new instance of Server created for every user connected, the variable is mutual for everyone. 这暗示着一个事实,尽管有一个为连接的每个用户创建的Server的新实例,但变量对于每个人都是相互的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM