I hate asking such a vague question, but I'm having a hard time finding a simple example. Here's what I have so far:
public class JettyWebSocketServlet extends WebSocketServlet{
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(MyEchoSocket.class);
}
}
@WebSocket
public class MyEchoSocket {
@OnWebSocketMessage
public void onText(WebSocketConnection conn, String message) {
System.out.println("text: " + message);
try {
conn.write(null, new FutureCallback(), "got: " + message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The embedded Jetty examples I can find always show something like the following, to start a Server instance running, but I don't know how to instantiate my WebSocketServlet.
Server server = new Server(8080);
server.start();
server.join();
How do I create an embedded server that can handle WebSocket connection requests?
Update: Oct 17, 2024
The Eclipse Jetty project has it's own top level github organization now.
The examples from the old organization have been merged together into a new examples project.
https://github.com/jetty/jetty-examples/
There are branches for Jetty versions 12.0.x
, 11.0.x
, 10.0.x
, and 9.4.x
at this point in time (soon there will be a 12.1.x
branch).
Each has their own /embedded/
sub-tree, check that for example on how to use websocket in an embedded sense.
For Jetty 12, for example, you have two choices.
/embedded/ee10-websocket-jakarta-api/
- for users wanting jakarta.websocket
API/embedded/ee10-websocket-jetty-api/
- for users wanting the org.eclipse.jetty.websocket
API.Update: Dec 2, 2013
For an up to date example of the Embedded Jetty with WebSocket see:
https://github.com/jetty-project/embedded-jetty-websocket-examples
Original Answer
There's an example found in the test cases.
Short Answer:
Server server = new Server(8080);
WebSocketHandler wsHandler = new WebSocketHandler()
{
@Override
public void configure(WebSocketServletFactory factory)
{
factory.register(MyEchoSocket.class);
}
};
server.addHandler(wsHandler);
server.start();
server.join();
This will create a simple server that handles 1 context, the root context.
http://localhost:8080/
If you want to bind the WebSocketHandler to another context, wrap it in a ContextHandler.
Server server = new Server(8080);
WebSocketHandler wsHandler = new WebSocketHandler()
{
@Override
public void configure(WebSocketServletFactory factory)
{
factory.register(MyEchoSocket.class);
}
};
ContextHandler context = new ContextHandler();
context.setContextPath("/echo");
context.setHandler(wsHandler);
server.addHandler(context);
server.start();
server.join();
This will bind your websocket to
http://localhost:8080/echo/