org.eclipse.jetty.websocket.WebSocket Java Examples

The following examples show how to use org.eclipse.jetty.websocket.WebSocket. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSocketAcceptorServlet.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
WebSocketConnection toWebSocketConnection(final WebSocket.Connection connection) {
    return new WebSocketConnection() {
        @Override
        public void write(String data) throws IOException {
            connection.sendMessage(data);
        }

        @Override
        public void disconnect() {
            connection.disconnect();
        }

        @Override
        public boolean isOpen() {
            return connection.isOpen();
        }

        @Override
        public void setMaxIdleTime(int ms) {
            connection.setMaxIdleTime(ms);
        }
    };
}
 
Example #2
Source File: PubSubWebSocketServlet.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
{
  @SuppressWarnings("unchecked")
  PRINCIPAL principal = (PRINCIPAL)request.getAttribute(authAttribute);
  return new PubSubWebSocket(principal);
}
 
Example #3
Source File: WebSocketAcceptorServlet.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 构造模块的WebSocket通讯连接
 * <p>对应的模块必须实现了{@link WebSocketAcceptor}接口</p>
 * <p>访问的路径为/sandbox/module/websocket/MODULE_NAME</p>
 *
 * @param req      req
 * @param protocol websocket protocol
 * @return WebSocket
 */
@Override
public WebSocket doWebSocketConnect(final HttpServletRequest req,
                                    final String protocol) {

    final String uniqueId = parseUniqueId(req.getPathInfo());
    if (StringUtils.isBlank(uniqueId)) {
        logger.warn("websocket value={} is illegal.", req.getPathInfo());
        return null;
    }

    final CoreModule coreModule = coreModuleManager.get(uniqueId);
    if (null == coreModule) {
        logger.warn("module[id={};] was not existed.", uniqueId);
        return null;
    }

    if (!(coreModule.getModule() instanceof WebSocketAcceptor)) {
        logger.warn("module[id={};class={};] is not implements WebSocketAcceptor.",
                uniqueId, coreModule.getModule().getClass().getName());
        return null;
    }

    final WebSocketConnectionListener listener =
            ((WebSocketAcceptor) coreModule.getModule()).onAccept(req, protocol);
    logger.info("accept websocket connection, module[id={};class={};], value={};",
            uniqueId, coreModule.getModule().getClass().getName(), req.getPathInfo());

    if (listener instanceof TextMessageListener) {
        return new InnerOnTextMessage(coreModule, (TextMessageListener) listener);
    } else {
        return new InnerWebSocket(coreModule, listener);
    }
}
 
Example #4
Source File: PubSubWebSocketServlet.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
{
  @SuppressWarnings("unchecked")
  PRINCIPAL principal = (PRINCIPAL)request.getAttribute(authAttribute);
  return new PubSubWebSocket(principal);
}
 
Example #5
Source File: StramTestSupport.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
public void start() throws Exception
{
  server = new Server();
  Connector connector = new SelectChannelConnector();
  connector.setPort(port);
  server.addConnector(connector);

    // Setup the basic application "context" for this application at "/"
  // This is also known as the handler tree (in jetty speak)
  ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
  contextHandler.setContextPath("/");
  server.setHandler(contextHandler);
  WebSocketServlet webSocketServlet = new WebSocketServlet()
  {
    @Override
    public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
    {
      return websocket;
    }
  };

  contextHandler.addServlet(new ServletHolder(webSocketServlet), "/pubsub");
  server.start();
  if (port == 0) {
    port = server.getConnectors()[0].getLocalPort();
  }
}
 
Example #6
Source File: WebSocketServerInputOperatorTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleTest() throws Exception
{
  final int port = 6666;
  String connectionURI = "ws://localhost:" + port + WebSocketServerInputOperator.DEFAULT_EXTENSION;

  final String message = "hello world";

  WebSocketServerInputOperator wssio = new TestWSSIO();
  wssio.setPort(port);
  wssio.setup(null);

  WebSocketClientFactory clientFactory = new WebSocketClientFactory();
  clientFactory.start();
  WebSocketClient client = new WebSocketClient(clientFactory);

  Future<WebSocket.Connection> connectionFuture = client.open(new URI(connectionURI), new TestWebSocket());
  WebSocket.Connection connection = connectionFuture.get(5, TimeUnit.SECONDS);

  connection.sendMessage(message);

  long startTime = System.currentTimeMillis();

  while (startTime + 10000 > System.currentTimeMillis()) {
    if (TestWSSIO.messages.size() >= 1) {
      break;
    }
    Thread.sleep(100);
  }

  Assert.assertEquals("The number of messages recieved is incorrect.", 1, TestWSSIO.messages.size());
  Assert.assertEquals("Incorrect message received", message, TestWSSIO.messages.get(0));

  connection.close();
  wssio.teardown();
}
 
Example #7
Source File: WebSocketSampler.java    From jmeter-websocket with Apache License 2.0 5 votes vote down vote up
@Override
public void testEnded(String host) {
    try {
        for(WebSocket.Connection connection : samplerConnections) {
            connection.close();
        }
        webSocketClientFactory.stop();
    } catch (Exception e) {
        log.error("sampler error when close.", e);
    }
}
 
Example #8
Source File: StramTestSupport.java    From attic-apex-core with Apache License 2.0 4 votes vote down vote up
public void setWebSocket(WebSocket websocket)
{
  this.websocket = websocket;
}
 
Example #9
Source File: WebSocketServerInputOperator.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
{
  return new DataSinkWebSocket();
}
 
Example #10
Source File: SamplePubSubWebSocketServlet.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Override
public WebSocket doWebSocketConnect(HttpServletRequest hsr, String string)
{
  return new PubSubWebSocket();
}
 
Example #11
Source File: ViewerServlet.java    From websockets-log-tail with Apache License 2.0 4 votes vote down vote up
@Override
public WebSocket doWebSocketConnect(HttpServletRequest req, String protocol) {
	return new StreamWebSocket(Util.createDummyStream());
}
 
Example #12
Source File: FileTailerServlet.java    From websockets-log-tail with Apache License 2.0 4 votes vote down vote up
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request,
		String protocol) {
	FileTailer tailer = new FileTailer(new File("/var/log/syslog"));
	return new StreamWebSocket(tailer.getStream(1000));
}
 
Example #13
Source File: WebSocketListener.java    From spring-integration-aws with MIT License 4 votes vote down vote up
@Override
public void start() {

	SelectChannelConnector wsConnector = new SelectChannelConnector();
	wsConnector.setHost(listenAddress);
	wsConnector.setPort(listenPort);
	wsConnector.setName("webSocket");
	wsConnector.setThreadPool(new QueuedThreadPool(10));
	server.setConnectors(new Connector[] { wsConnector });
	server.setHandler(new WebSocketHandler() {

		@Override
		public WebSocket doWebSocketConnect(HttpServletRequest request,
				String protocol) {

			log.debug("Request path:" + request.getRequestURI());
			String beanName = request.getRequestURI().replaceFirst("\\/",
					"");
			final WebsocketHandler handler = applicationContext.getBean(
					beanName, WebsocketHandler.class);

			return new WebSocket.OnTextMessage() {

				@Override
				public void onOpen(Connection connection) {
					connection.setMaxIdleTime(3600000);
					handler.setConnection(connection);
					handler.start();
				}

				@Override
				public void onClose(int code, String message) {
					handler.stop();
					log.info("Connection closed.");
				}

				@Override
				public void onMessage(String data) {
					handler.postMessage(data);
				}
			};
		}
	});

	serverThread.execute(new Runnable() {

		@Override
		public void run() {
			try {
				server.start();
				server.join();
			} catch (Exception e) {
				log.warn(e.getMessage(), e);
			}
		}
	});
}