Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do websockets in embedded undertow?

According to this: http://undertow.io/ it supports websockets. There is no documentation on how to do so, though. I just want a simple embedded undertow handling web sockets example.

I don't want to grab the whole jboss app server.

like image 944
mentics Avatar asked Aug 06 '13 00:08

mentics


2 Answers

Take a look at undertow examples

chat: https://github.com/undertow-io/undertow/tree/master/examples/src/main/java/io/undertow/examples/chat

and websockets example https://github.com/undertow-io/undertow/tree/master/examples/src/main/java/io/undertow/examples/websockets

this will help you.

like image 91
Tomaz Cerar Avatar answered Oct 05 '22 20:10

Tomaz Cerar


I'm came up with this class. However, I am not an JBoss expert. I'm especially uncertain about the xnio stuff.

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

}
like image 45
Johannes Barop Avatar answered Oct 05 '22 18:10

Johannes Barop