如何使用Struts 2实现Websocket

Alv*_*ian 5 java struts2 comet websocket

我目前正在使用Struts 2作为框架,并且需要具有Websocket功能,以便可以与通过HTML Websocket访问它的客户端进行通信。

我试图将Java Websocket API(JSR 356)与在Tomcat 7.0.56上运行的Java应用程序一起使用。但是,当我在Struts 2框架上尝试时,它不起作用。

我所做的一些研究表明,可能是因为Struts 2映射URL的方式,但无济于事,我仍然无法与服务器上的Websocket端点进行通信。

有谁知道如何使用Struts 2框架实现Websocket?

我用于websocket的代码如下:

@ServerEndpoint("/mssendpoint")
public class MSSEndpoint {

    public static Logger logger = Logger.getLogger(MSSEndpoint.class);

    /* Queue for all open WebSocket sessions */
    static Queue<Session> queue = new ConcurrentLinkedQueue<Session>();

    static Set<WebsocketListener> listeners = new HashSet<WebsocketListener>();

    public static void send(String msg) {
        try {
            /* Send updates to all open WebSocket sessions */
            for (Session session : queue) {
                session.getBasicRemote().sendText(msg);
                logger.info("Sent: " + msg);
            }
        }
        catch (IOException e) {
            logger.error(e.toString());
        }
    }

    @OnOpen
    public void openConnection(Session session) {
        /* Register this connection in the queue */
        queue.add(session);
        logger.info("Connection opened.");
    }

    @OnClose
    public void closedConnection(Session session) {
        /* Remove this connection from the queue */
        queue.remove(session);
        logger.info("Connection closed.");
    }

    @OnError
    public void error(Session session, Throwable t) {
        /* Remove this connection from the queue */
        queue.remove(session);
        logger.info(t.toString());
        logger.info("Connection error.");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        if (queue.contains(session)) {
            notifyListener(message);
        }
    }

    public static void addListener(WebsocketListener listener){
        listeners.add(listener);
    }

    public static void removeListener(WebsocketListener listener){
        listeners.remove(listener);
    }

    public void notifyListener(String message){
        for (WebsocketListener listener : listeners) {
            listener.onMessage(message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经在运行于Tomcat 7.0.56的普通Java Servlet应用程序上使用了完全相同的代码,并且通过客户端,我可以连接到它。

我使用“简单Websocket客户端” chrome扩展程序作为客户端。

我需要的只是连接到ws://localhost/myprojectname/mssendpoint它,它将直接连接。

EDIT2:我忘了提一下错误是,当我尝试连接时,它只是说说undefined我在使用Websocket Client。假设我的Struts 2项目被调用cms,我应该只需要访问ws://localhost/myprojectname/mssendpoint。但随后产生了该undefined消息。