View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.embedded;
20  
21  import org.eclipse.jetty.server.Server;
22  import org.eclipse.jetty.servlet.ServletContextHandler;
23  import org.eclipse.jetty.servlet.ServletHolder;
24  import org.eclipse.jetty.websocket.api.Session;
25  import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
26  import org.eclipse.jetty.websocket.api.annotations.WebSocket;
27  import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
28  import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
29  
30  /**
31   * Example of setting up a Jetty WebSocket server
32   * <p>
33   * Note: this uses the Jetty WebSocket API, not the javax.websocket API.
34   */
35  public class WebSocketServer
36  {
37      /**
38       * Example of a Jetty API WebSocket Echo Socket
39       */
40      @WebSocket
41      public static class EchoSocket
42      {
43          @OnWebSocketMessage
44          public void onMessage( Session session, String message )
45          {
46              session.getRemote().sendStringByFuture(message);
47          }
48      }
49  
50      /**
51       * Servlet layer
52       */
53      @SuppressWarnings("serial")
54      public static class EchoServlet extends WebSocketServlet
55      {
56          @Override
57          public void configure( WebSocketServletFactory factory )
58          {
59              // Register the echo websocket with the basic WebSocketCreator
60              factory.register(EchoSocket.class);
61          }
62      }
63  
64      public static void main( String[] args ) throws Exception
65      {
66          Server server = new Server(8080);
67  
68          ServletContextHandler context = new ServletContextHandler(
69                  ServletContextHandler.SESSIONS);
70          context.setContextPath("/");
71          server.setHandler(context);
72  
73          // Add the echo socket servlet to the /echo path map
74          context.addServlet(new ServletHolder(EchoServlet.class), "/echo");
75  
76          server.start();
77          context.dumpStdErr();
78          server.join();
79      }
80  }