Search in sources :

Example 1 with WebSocketSession

use of org.eclipse.jetty.websocket.common.WebSocketSession in project jetty.project by eclipse.

the class SessionTest method testBasicEcho_FromClient.

@Test
// TODO fix frequent failure
@Ignore
public void testBasicEcho_FromClient() throws Exception {
    WebSocketClient client = new WebSocketClient();
    client.start();
    try {
        JettyTrackingSocket cliSock = new JettyTrackingSocket();
        client.getPolicy().setIdleTimeout(10000);
        URI wsUri = server.getWsUri();
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setSubProtocols("echo");
        Future<Session> future = client.connect(cliSock, wsUri, request);
        final IBlockheadServerConnection srvSock = server.accept();
        srvSock.upgrade();
        Session sess = future.get(30000, TimeUnit.MILLISECONDS);
        Assert.assertThat("Session", sess, notNullValue());
        Assert.assertThat("Session.open", sess.isOpen(), is(true));
        Assert.assertThat("Session.upgradeRequest", sess.getUpgradeRequest(), notNullValue());
        Assert.assertThat("Session.upgradeResponse", sess.getUpgradeResponse(), notNullValue());
        cliSock.assertWasOpened();
        cliSock.assertNotClosed();
        Collection<WebSocketSession> sessions = client.getBeans(WebSocketSession.class);
        Assert.assertThat("client.connectionManager.sessions.size", sessions.size(), is(1));
        RemoteEndpoint remote = cliSock.getSession().getRemote();
        remote.sendStringByFuture("Hello World!");
        if (remote.getBatchMode() == BatchMode.ON) {
            remote.flush();
        }
        srvSock.echoMessage(1, 30000, TimeUnit.MILLISECONDS);
        // wait for response from server
        cliSock.waitForMessage(30000, TimeUnit.MILLISECONDS);
        Set<WebSocketSession> open = client.getOpenSessions();
        Assert.assertThat("(Before Close) Open Sessions.size", open.size(), is(1));
        cliSock.assertMessage("Hello World!");
        cliSock.close();
        srvSock.close();
        cliSock.waitForClose(30000, TimeUnit.MILLISECONDS);
        open = client.getOpenSessions();
        // TODO this sometimes fails!
        Assert.assertThat("(After Close) Open Sessions.size", open.size(), is(0));
    } finally {
        client.stop();
    }
}
Also used : IBlockheadServerConnection(org.eclipse.jetty.websocket.common.test.IBlockheadServerConnection) RemoteEndpoint(org.eclipse.jetty.websocket.api.RemoteEndpoint) URI(java.net.URI) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Session(org.eclipse.jetty.websocket.api.Session) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 2 with WebSocketSession

use of org.eclipse.jetty.websocket.common.WebSocketSession in project jetty.project by eclipse.

the class WebSocketUpgradeRequest method upgrade.

@Override
public void upgrade(HttpResponse response, HttpConnectionOverHTTP oldConn) {
    if (!this.getHeaders().get(HttpHeader.UPGRADE).equalsIgnoreCase("websocket")) {
        // Not my upgrade
        throw new HttpResponseException("Not WebSocket Upgrade", response);
    }
    // Check the Accept hash
    String reqKey = this.getHeaders().get(HttpHeader.SEC_WEBSOCKET_KEY);
    String expectedHash = AcceptHash.hashKey(reqKey);
    String respHash = response.getHeaders().get(HttpHeader.SEC_WEBSOCKET_ACCEPT);
    if (expectedHash.equalsIgnoreCase(respHash) == false) {
        throw new HttpResponseException("Invalid Sec-WebSocket-Accept hash", response);
    }
    // We can upgrade
    EndPoint endp = oldConn.getEndPoint();
    WebSocketClientConnection connection = new WebSocketClientConnection(endp, wsClient.getExecutor(), wsClient.getScheduler(), localEndpoint.getPolicy(), wsClient.getBufferPool());
    URI requestURI = this.getURI();
    WebSocketSession session = getSessionFactory().createSession(requestURI, localEndpoint, connection);
    session.setUpgradeRequest(new ClientUpgradeRequest(this));
    session.setUpgradeResponse(new ClientUpgradeResponse(response));
    connection.addListener(session);
    ExtensionStack extensionStack = new ExtensionStack(getExtensionFactory());
    List<ExtensionConfig> extensions = new ArrayList<>();
    HttpField extField = response.getHeaders().getField(HttpHeader.SEC_WEBSOCKET_EXTENSIONS);
    if (extField != null) {
        String[] extValues = extField.getValues();
        if (extValues != null) {
            for (String extVal : extValues) {
                QuotedStringTokenizer tok = new QuotedStringTokenizer(extVal, ",");
                while (tok.hasMoreTokens()) {
                    extensions.add(ExtensionConfig.parse(tok.nextToken()));
                }
            }
        }
    }
    extensionStack.negotiate(extensions);
    extensionStack.configure(connection.getParser());
    extensionStack.configure(connection.getGenerator());
    // Setup Incoming Routing
    connection.setNextIncomingFrames(extensionStack);
    extensionStack.setNextIncoming(session);
    // Setup Outgoing Routing
    session.setOutgoingHandler(extensionStack);
    extensionStack.setNextOutgoing(connection);
    session.addManaged(extensionStack);
    session.setFuture(fut);
    wsClient.addManaged(session);
    if (upgradeListener != null) {
        upgradeListener.onHandshakeResponse(new ClientUpgradeResponse(response));
    }
    // Now swap out the connection
    endp.upgrade(connection);
}
Also used : ArrayList(java.util.ArrayList) WebSocketClientConnection(org.eclipse.jetty.websocket.client.io.WebSocketClientConnection) HttpResponseException(org.eclipse.jetty.client.HttpResponseException) EndPoint(org.eclipse.jetty.io.EndPoint) URI(java.net.URI) ExtensionStack(org.eclipse.jetty.websocket.common.extensions.ExtensionStack) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer) ExtensionConfig(org.eclipse.jetty.websocket.api.extensions.ExtensionConfig) HttpField(org.eclipse.jetty.http.HttpField)

Example 3 with WebSocketSession

use of org.eclipse.jetty.websocket.common.WebSocketSession in project chassis by Kixeye.

the class WebSocketTransportTest method testEmptyWebSocketFrameUsingText.

@Test
public void testEmptyWebSocketFrameUsingText() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");
    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestWebSocketService.class);
    WebSocketClient wsClient = new WebSocketClient();
    try {
        //start server
        context.refresh();
        // start client
        wsClient.start();
        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
        QueuingWebSocketListener listener = new QueuingWebSocketListener(serDe, messageRegistry, null);
        WebSocketSession session = (WebSocketSession) wsClient.connect(listener, new URI("ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())).get(5000, TimeUnit.MILLISECONDS);
        session.getRemote().sendString("");
        ServiceError error = listener.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(error);
        Assert.assertEquals("EMPTY_ENVELOPE", error.code);
        Assert.assertEquals("STOPPED", session.getState());
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}
Also used : ServiceError(com.kixeye.chassis.transport.dto.ServiceError) HashMap(java.util.HashMap) WebSocketMessageRegistry(com.kixeye.chassis.transport.websocket.WebSocketMessageRegistry) JsonJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe) ProtobufMessageSerDe(com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe) YamlJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe) XmlMessageSerDe(com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) URI(java.net.URI) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) MapPropertySource(org.springframework.core.env.MapPropertySource) QueuingWebSocketListener(com.kixeye.chassis.transport.websocket.QueuingWebSocketListener) StandardEnvironment(org.springframework.core.env.StandardEnvironment) Test(org.junit.Test)

Example 4 with WebSocketSession

use of org.eclipse.jetty.websocket.common.WebSocketSession in project chassis by Kixeye.

the class WebSocketTransportTest method testEmptyWebSocketFrameUsingBinary.

@Test
public void testEmptyWebSocketFrameUsingBinary() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");
    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestWebSocketService.class);
    WebSocketClient wsClient = new WebSocketClient();
    try {
        //start server
        context.refresh();
        // start client
        wsClient.start();
        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
        QueuingWebSocketListener listener = new QueuingWebSocketListener(serDe, messageRegistry, null);
        WebSocketSession session = (WebSocketSession) wsClient.connect(listener, new URI("ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())).get(5000, TimeUnit.MILLISECONDS);
        session.getRemote().sendBytes(ByteBuffer.wrap(new byte[0]));
        ServiceError error = listener.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(error);
        Assert.assertEquals("EMPTY_ENVELOPE", error.code);
        Assert.assertEquals("STOPPED", session.getState());
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}
Also used : ServiceError(com.kixeye.chassis.transport.dto.ServiceError) HashMap(java.util.HashMap) WebSocketMessageRegistry(com.kixeye.chassis.transport.websocket.WebSocketMessageRegistry) JsonJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe) ProtobufMessageSerDe(com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe) YamlJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe) XmlMessageSerDe(com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) URI(java.net.URI) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) MapPropertySource(org.springframework.core.env.MapPropertySource) QueuingWebSocketListener(com.kixeye.chassis.transport.websocket.QueuingWebSocketListener) StandardEnvironment(org.springframework.core.env.StandardEnvironment) Test(org.junit.Test)

Example 5 with WebSocketSession

use of org.eclipse.jetty.websocket.common.WebSocketSession in project jetty.project by eclipse.

the class SessionTrackingTest method testAddRemoveSessions.

@Test
public void testAddRemoveSessions() throws Exception {
    // Create Client
    ClientContainer clientContainer = new ClientContainer();
    QueuedThreadPool clientThreads = new QueuedThreadPool();
    clientThreads.setName("client");
    clientContainer.getClient().setExecutor(clientThreads);
    try {
        CountDownLatch openedLatch = new CountDownLatch(2);
        CountDownLatch closedLatch = new CountDownLatch(2);
        wsServerFactory.addSessionListener(new WebSocketSession.Listener() {

            @Override
            public void onOpened(WebSocketSession session) {
                openedLatch.countDown();
            }

            @Override
            public void onClosed(WebSocketSession session) {
                closedLatch.countDown();
            }
        });
        clientContainer.start();
        // Establish connections
        ClientSocket cli1 = new ClientSocket();
        clientContainer.connectToServer(cli1, serverURI.resolve("/test"));
        cli1.waitForOpen(1, TimeUnit.SECONDS);
        // Establish new connection
        ClientSocket cli2 = new ClientSocket();
        clientContainer.connectToServer(cli2, serverURI.resolve("/test"));
        cli2.waitForOpen(1, TimeUnit.SECONDS);
        openedLatch.await(5, TimeUnit.SECONDS);
        assertServerOpenConnectionCount(2);
        // Establish close both connections
        cli1.session.close();
        cli2.session.close();
        cli1.waitForClose(1, TimeUnit.SECONDS);
        cli2.waitForClose(1, TimeUnit.SECONDS);
        closedLatch.await(5, TimeUnit.SECONDS);
        assertServerOpenConnectionCount(0);
    } finally {
        clientContainer.stop();
    }
}
Also used : QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ClientContainer(org.eclipse.jetty.websocket.jsr356.ClientContainer) CountDownLatch(java.util.concurrent.CountDownLatch) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Test(org.junit.Test)

Aggregations

WebSocketSession (org.eclipse.jetty.websocket.common.WebSocketSession)8 URI (java.net.URI)6 Test (org.junit.Test)6 Session (org.eclipse.jetty.websocket.api.Session)3 IBlockheadServerConnection (org.eclipse.jetty.websocket.common.test.IBlockheadServerConnection)3 ServiceError (com.kixeye.chassis.transport.dto.ServiceError)2 MessageSerDe (com.kixeye.chassis.transport.serde.MessageSerDe)2 JsonJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe)2 ProtobufMessageSerDe (com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe)2 XmlMessageSerDe (com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe)2 YamlJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe)2 QueuingWebSocketListener (com.kixeye.chassis.transport.websocket.QueuingWebSocketListener)2 WebSocketMessageRegistry (com.kixeye.chassis.transport.websocket.WebSocketMessageRegistry)2 HashMap (java.util.HashMap)2 EndPoint (org.eclipse.jetty.io.EndPoint)2 RemoteEndpoint (org.eclipse.jetty.websocket.api.RemoteEndpoint)2 WebSocketClient (org.eclipse.jetty.websocket.client.WebSocketClient)2 ExtensionStack (org.eclipse.jetty.websocket.common.extensions.ExtensionStack)2 MapPropertySource (org.springframework.core.env.MapPropertySource)2 StandardEnvironment (org.springframework.core.env.StandardEnvironment)2