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