下面列出了怎么用java.net.http.WebSocket.Listener的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testCloseChannel() throws Exception {
//given
final HttpClient httpClient = HttpClient.newHttpClient();
final Config config = Application.getInstance(Config.class);
final String url = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocket";
final WebSocketService webSocketService = Application.getInstance(WebSocketService.class);
webSocketService.removeChannels("/websocket");
// when
Listener listener = new Listener() {
@Override
public void onOpen(WebSocket webSocket) {
}
};
httpClient.newWebSocketBuilder().buildAsync(new URI(url), listener).join();
webSocketService.close("/websocket");
//then
assertThat(webSocketService.getChannels("/websocket"), not(nullValue()));
assertThat(webSocketService.getChannels("/websocket").size(), equalTo(0));
}
@Test
public void testWebSocketConnection() throws Exception {
// given
final HttpClient httpClient = HttpClient.newHttpClient();
final Config config = Application.getInstance(Config.class);
final String uri = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocket";
// when
Listener listener = new Listener() {
@Override
public void onOpen(WebSocket webSocket) {
connected = true;
}
};
httpClient.newWebSocketBuilder().buildAsync(new URI(uri), listener).join();
// then
assertThat(connected, equalTo(true));
}
@Override
public CompletionStage onText(WebSocket webSocket, CharSequence data, boolean last) {
System.out.println("Method onText() got data: " + data);
if(!webSocket.isOutputClosed()) {
webSocket.sendText("Another message", true);
}
return Listener.super.onText(webSocket, data, last);
}
@Test
public void testSendData() throws Exception {
// given
final HttpClient httpClient = HttpClient.newHttpClient();
final Config config = Application.getInstance(Config.class);
final String url = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocket";
final String data = UUID.randomUUID().toString();
eventData = null;
// when
Listener listener = new Listener() {
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence message, boolean last) {
eventData = message.toString();
return null;
}
};
httpClient.newWebSocketBuilder().buildAsync(new URI(url), listener).get();
Application.getInstance(WebSocketService.class).getChannels("/websocket").forEach(channel -> {
try {
if (channel.isOpen()) {
WebSockets.sendTextBlocking(data, channel);
}
} catch (final IOException e) {
e.printStackTrace();
}
});
//then
await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> assertThat(eventData, equalTo(data)));
}
@Test
public void testSendDataWithInvalidAuthentication() throws Exception {
// given
final HttpClient httpClient = HttpClient.newHttpClient();
final Config config = Application.getInstance(Config.class);
final String url = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocketauth";
final String data = UUID.randomUUID().toString();
eventData = null;
PasetoV1LocalBuilder token = Pasetos.V1.LOCAL.builder().setSubject("foo")
.setExpiration(LocalDateTime.now().plusHours(1).atZone(ZoneId.systemDefault()).toInstant())
.claim(ClaimKey.TWO_FACTOR.toString(), "false")
.setSharedSecret(new SecretKeySpec("oskdlwsodkcmansjdkwsowekd5jfvsq2mckdkalsodkskajsfdsfdsfvvkdkcskdsqidsjk".getBytes(StandardCharsets.UTF_8), "AES"));
Listener listener = new Listener() {
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence message, boolean last) {
eventData = message.toString();
return null;
}
};
httpClient.newWebSocketBuilder()
.header("Cookie", config.getAuthenticationCookieName() + "=" + token.compact())
.buildAsync(new URI(url), listener);
await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> assertThat(eventData, not(equalTo(data))));
Application.getInstance(WebSocketService.class).getChannels("/websocketauth").forEach(channel -> {
try {
if (channel.isOpen()) {
WebSockets.sendTextBlocking(data, channel);
}
} catch (final IOException e) {
e.printStackTrace();
}
});
// then
await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> assertThat(eventData, not(equalTo(data))));
}
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("Connection established.");
webSocket.sendText("Some message", true);
Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("Closed with status " + statusCode + ", reason: " + reason);
return Listener.super.onClose(webSocket, statusCode, reason);
}
@Test
public void testSendDataWithValidAuthentication() throws Exception {
// given
final HttpClient httpClient = HttpClient.newHttpClient();
final Config config = Application.getInstance(Config.class);
final String url = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocketauth";
final String data = UUID.randomUUID().toString();
eventData = null;
// then
PasetoV1LocalBuilder token = Pasetos.V1.LOCAL.builder().setSubject("foo")
.setExpiration(LocalDateTime.now().plusHours(1).atZone(ZoneId.systemDefault()).toInstant())
.claim(ClaimKey.TWO_FACTOR.toString(), "false")
.setSharedSecret(new SecretKeySpec(config.getAuthenticationCookieSecret().getBytes(StandardCharsets.UTF_8), "AES"));
Listener listener = new Listener() {
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence message, boolean last) {
eventData = message.toString();
return null;
}
};
httpClient.newWebSocketBuilder()
.header("Cookie", config.getAuthenticationCookieName() + "=" + token.compact())
.buildAsync(new URI(url), listener);
await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> assertThat(eventData, not(equalTo(data))));
Application.getInstance(WebSocketService.class).getChannels("/websocketauth").forEach(channel -> {
try {
if (channel.isOpen()) {
WebSockets.sendTextBlocking(data, channel);
}
} catch (final IOException e) {
e.printStackTrace();
}
});
// then
await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> assertThat(eventData, equalTo(data)));
}