如何在嵌入式底板中做websockets?

时间:2013-08-06 00:22:21

标签: java jboss websocket wildfly undertow

根据:http://undertow.io/它支持websockets。但是,没有关于如何这样做的文档。我只想要一个处理Web套接字示例的简单嵌入式底层。

我不想抓住整个jboss应用服务器。

2 个答案:

答案 0 :(得分:5)

答案 1 :(得分:4)

我想出了这堂课。但是,我不是JBoss专家。我对xnio的东西特别不确定。

import io.undertow.Undertow;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.jboss.logging.Logger;
import org.xnio.OptionMap;
import org.xnio.Xnio;
import org.xnio.XnioWorker;

import javax.servlet.ServletException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

import static io.undertow.servlet.Servlets.defaultContainer;
import static io.undertow.servlet.Servlets.deployment;
import static io.undertow.websockets.jsr.WebSocketDeploymentInfo.ATTRIBUTE_NAME;

public class WebsocketServer {

  private static final Logger LOGGER = Logger.getLogger(WebsocketServer.class);

  @ServerEndpoint("/")
  public static class SocketProxy {

    @OnOpen
    public void onOpen() {
      LOGGER.info("onOpen");
    }

    @OnClose
    public void onClose() {
      LOGGER.info("onClose");
    }

    @OnMessage
    public void onMessage(String message) {
      LOGGER.info("onMessage:" + message);
    }

  }

  public static void main(String[] args) throws ServletException, IOException {
    final Xnio xnio = Xnio.getInstance("nio", Undertow.class.getClassLoader());
    final XnioWorker xnioWorker = xnio.createWorker(OptionMap.builder().getMap());
    final WebSocketDeploymentInfo webSockets = new WebSocketDeploymentInfo()
        .addEndpoint(SocketProxy.class)
        .setWorker(xnioWorker);
    final DeploymentManager deployment = defaultContainer()
        .addDeployment(deployment()
            .setClassLoader(WebsocketServer.class.getClassLoader())
            .setContextPath("/")
            .setDeploymentName("embedded-websockets")
            .addServletContextAttribute(ATTRIBUTE_NAME, webSockets));

    deployment.deploy();
    Undertow.builder().
        addListener(8080, "localhost")
        .setHandler(deployment.start())
        .build()
        .start();
  }

}