Search in sources :

Example 1 with SimpleWsObject

use of org.mx.service.server.websocket.SimpleWsObject in project main by JohnPeng739.

the class WebsocketServerFactory method afterPropertiesSet.

/**
 * {@inheritDoc}
 *
 * @see InitializingBean#afterPropertiesSet()
 */
@Override
public void afterPropertiesSet() throws Exception {
    boolean enabled = env.getProperty("websocket.enabled", Boolean.class, true);
    if (!enabled) {
        // 显式配置enable为false,表示不进行初始化。
        return;
    }
    final int port = env.getProperty("websocket.port", Integer.class, 9997);
    String websocketClassesStr = "websocket.service.classes";
    String websocketServiceClassesDef = this.env.getProperty(websocketClassesStr);
    if (StringUtils.isBlank(websocketServiceClassesDef)) {
        if (logger.isWarnEnabled()) {
            logger.warn(String.format("You not define [%s], will not ", websocketClassesStr));
        }
    } else {
        String[] classesDefs = websocketServiceClassesDef.split(",");
        for (String classesDef : classesDefs) {
            if (!StringUtils.isBlank(classesDef)) {
                List<Class<?>> websocketClasses = (List) this.context.getBean(classesDef, List.class);
                if (websocketClasses != null && !websocketClasses.isEmpty()) {
                    websocketClasses.forEach((clazz) -> {
                        WsSessionListener listener = (WsSessionListener) context.getBean(clazz);
                        socketBeans.put(listener.getPath(), new SimpleWsObject(listener));
                    });
                }
            }
        }
        Server server = new Server(port);
        server.setHandler(new WebSocketHandler() {

            @Override
            public void configure(WebSocketServletFactory factory) {
                factory.setCreator(new MyWebsocketCreator());
            }
        });
        server.setStopAtShutdown(true);
        server.setStopTimeout(10);
        super.setServer(server);
        server.start();
        if (logger.isInfoEnabled()) {
            logger.info(String.format("Start Websocket server success, listen port: %d.", port));
        }
    }
}
Also used : WebSocketServletFactory(org.eclipse.jetty.websocket.servlet.WebSocketServletFactory) Server(org.eclipse.jetty.server.Server) SimpleWsObject(org.mx.service.server.websocket.SimpleWsObject) WebSocketHandler(org.eclipse.jetty.websocket.server.WebSocketHandler) List(java.util.List) WsSessionListener(org.mx.service.server.websocket.WsSessionListener)

Aggregations

List (java.util.List)1 Server (org.eclipse.jetty.server.Server)1 WebSocketHandler (org.eclipse.jetty.websocket.server.WebSocketHandler)1 WebSocketServletFactory (org.eclipse.jetty.websocket.servlet.WebSocketServletFactory)1 SimpleWsObject (org.mx.service.server.websocket.SimpleWsObject)1 WsSessionListener (org.mx.service.server.websocket.WsSessionListener)1