use of javax.websocket.CloseReason in project undertow by undertow-io.
the class WebsocketStressTestCase method websocketFragmentationStressTestCase.
@Test
public void websocketFragmentationStressTestCase() throws Exception {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final CountDownLatch done = new CountDownLatch(1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; ++i) {
sb.append("message ");
sb.append(i);
}
String toSend = sb.toString();
final Session session = defaultContainer.connectToServer(new Endpoint() {
@Override
public void onOpen(Session session, EndpointConfig config) {
session.addMessageHandler(new MessageHandler.Partial<byte[]>() {
@Override
public void onMessage(byte[] bytes, boolean b) {
try {
out.write(bytes);
} catch (IOException e) {
e.printStackTrace();
done.countDown();
}
if (b) {
done.countDown();
}
}
});
}
@Override
public void onClose(Session session, CloseReason closeReason) {
done.countDown();
}
@Override
public void onError(Session session, Throwable thr) {
thr.printStackTrace();
done.countDown();
}
}, null, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/stress"));
OutputStream stream = session.getBasicRemote().getSendStream();
for (int i = 0; i < toSend.length(); ++i) {
stream.write(toSend.charAt(i));
stream.flush();
}
stream.close();
done.await(40, TimeUnit.SECONDS);
Assert.assertEquals(toSend, new String(out.toByteArray()));
}
use of javax.websocket.CloseReason in project undertow by undertow-io.
the class WebsocketStressTestCase method webSocketStringStressTestCase.
@Test
public void webSocketStringStressTestCase() throws Exception {
List<CountDownLatch> latches = new ArrayList<>();
for (int i = 0; i < NUM_THREADS; ++i) {
final CountDownLatch latch = new CountDownLatch(1);
latches.add(latch);
final Session session = deployment.connectToServer(new Endpoint() {
@Override
public void onOpen(Session session, EndpointConfig config) {
}
@Override
public void onClose(Session session, CloseReason closeReason) {
latch.countDown();
}
@Override
public void onError(Session session, Throwable thr) {
latch.countDown();
}
}, null, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/stress"));
final int thread = i;
executor.submit(new Runnable() {
@Override
public void run() {
try {
executor.submit(new SendRunnable(session, thread, executor));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
for (CountDownLatch future : latches) {
future.await();
}
for (int t = 0; t < NUM_THREADS; ++t) {
for (int i = 0; i < NUM_REQUESTS; ++i) {
String msg = "t-" + t + "-m-" + i;
Assert.assertTrue(msg, StressEndpoint.MESSAGES.remove(msg));
}
}
Assert.assertEquals(0, StressEndpoint.MESSAGES.size());
}
use of javax.websocket.CloseReason in project undertow by undertow-io.
the class JsrWebSocketServer07Test method testCloseFrame.
@org.junit.Test
public void testCloseFrame() throws Exception {
final int code = 1000;
final String reasonText = "TEST";
final AtomicReference<CloseReason> reason = new AtomicReference<>();
ByteBuffer payload = ByteBuffer.allocate(reasonText.length() + 2);
payload.putShort((short) code);
payload.put(reasonText.getBytes("UTF-8"));
payload.flip();
final AtomicBoolean connected = new AtomicBoolean(false);
final FutureResult latch = new FutureResult();
final CountDownLatch clientLatch = new CountDownLatch(1);
final AtomicInteger closeCount = new AtomicInteger();
class TestEndPoint extends Endpoint {
@Override
public void onOpen(final Session session, EndpointConfig config) {
connected.set(true);
}
@Override
public void onClose(Session session, CloseReason closeReason) {
closeCount.incrementAndGet();
reason.set(closeReason);
clientLatch.countDown();
}
}
ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getWorker(), DefaultServer.getBufferPool(), Collections.EMPTY_LIST, false, false);
builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
deployServlet(builder);
WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
client.connect();
client.send(new CloseWebSocketFrame(code, reasonText), new FrameChecker(CloseWebSocketFrame.class, payload.array(), latch));
latch.getIoFuture().get();
clientLatch.await();
Assert.assertEquals(code, reason.get().getCloseCode().getCode());
Assert.assertEquals(reasonText, reason.get().getReasonPhrase());
Assert.assertEquals(1, closeCount.get());
client.destroy();
}
use of javax.websocket.CloseReason in project tomee by apache.
the class FileWatcher method watch.
public Closeable watch(final String folder) {
final File file = new File(folder);
if (!file.isDirectory()) {
throw new IllegalArgumentException(folder + " is not a directory");
}
try {
final AtomicBoolean again = new AtomicBoolean(true);
final Path path = file.getAbsoluteFile().toPath();
final WatchService watchService = path.getFileSystem().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
final Thread watcherThread = new Thread(new Runnable() {
@Override
public void run() {
while (again.get()) {
try {
// don't use take to not block forever
final WatchKey key = watchService.poll(1, TimeUnit.SECONDS);
if (key == null) {
continue;
}
for (final WatchEvent<?> event : key.pollEvents()) {
final WatchEvent.Kind<?> kind = event.kind();
if (kind != StandardWatchEventKinds.ENTRY_CREATE && kind != StandardWatchEventKinds.ENTRY_DELETE && kind != StandardWatchEventKinds.ENTRY_MODIFY) {
continue;
}
final Path updatedPath = Path.class.cast(event.context());
if (kind == StandardWatchEventKinds.ENTRY_DELETE || updatedPath.toFile().isFile()) {
final String path = updatedPath.toString();
if (path.endsWith("___jb_tmp___") || path.endsWith("___jb_old___")) {
continue;
} else if (path.endsWith("~")) {
onChange(path.replace(File.pathSeparatorChar, '/').substring(0, path.length() - 1));
} else {
onChange(path.replace(File.pathSeparatorChar, '/'));
}
}
}
key.reset();
} catch (final InterruptedException e) {
Thread.interrupted();
again.set(false);
} catch (final ClosedWatchServiceException cwse) {
// ok, we finished there
}
}
}
});
watcherThread.setName("livereload-tomee-watcher(" + folder + ")");
watcherThread.start();
return new Closeable() {
@Override
public void close() throws IOException {
synchronized (this) {
for (final Session s : sessions) {
removeSession(s);
try {
s.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "container shutdowned"));
} catch (final Exception e) {
// ok: not important there
}
}
}
again.compareAndSet(true, false);
try {
watchService.close();
} catch (final IOException ioe) {
logger.warning("Error closing the watch service for " + folder + "(" + ioe.getMessage() + ")");
}
try {
watcherThread.join(TimeUnit.MINUTES.toMillis(1));
} catch (final InterruptedException e) {
Thread.interrupted();
}
}
};
} catch (final IOException e) {
throw new IllegalArgumentException(e);
}
}
use of javax.websocket.CloseReason in project meecrowave by apache.
the class ChatWS method message.
@OnMessage
public void message(Session session, JsonObject msg) {
try {
if (!"ping".equals(msg.getString("chat"))) {
session.close(new CloseReason(CloseCodes.UNEXPECTED_CONDITION, String.format("unexpected chat value %s", msg.getString("chat"))));
}
JsonObject pong = Json.createObjectBuilder().add("chat", "pong " + chatCounter.incrementAndGet()).build();
session.getBasicRemote().sendObject(pong);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
Aggregations