如何使用Struts 2实现websocket

时间:2015-01-30 06:43:13

标签: java struts2 websocket comet

我目前正在使用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);
        }
    }
}

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

我使用'Simple Websocket Client'chrome扩展作为客户端。

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

EDIT2: 我忘了提到错误是当我尝试连接时,当我使用Websocket客户端时,它只会说undefined。假设我的Struts 2项目被称为cms,那么我应该只需要访问ws://localhost/myprojectname/mssendpoint。但随后它产生了undefined消息。

0 个答案:

没有答案
相关问题