use of javax.websocket.CloseReason in project tomcat70 by apache.
the class Client method sendMessage.
/**
* Sends the given message asynchronously to the client.
* If there is already a async sending in progress, then the message
* will be buffered and sent when possible.<br><br>
*
* This method can be called from multiple threads.
* @param msg
*/
public void sendMessage(AbstractWebsocketMessage msg) {
synchronized (messagesToSend) {
if (!isClosing) {
// Check if we have a Close message
if (msg instanceof CloseWebsocketMessage) {
isClosing = true;
}
if (isSendingMessage) {
// or length(of all messages) >= 1000000 bytes.
if (messagesToSend.size() >= 1000 || messagesToSendLength >= 1000000) {
isClosing = true;
// Discard the new message and close the session immediately.
CloseReason cr = new CloseReason(CloseCodes.VIOLATED_POLICY, "Send Buffer exceeded");
try {
// TODO: close() may block if the remote endpoint doesn't read the data
// (eventually there will be a TimeoutException). However, this method
// (sendMessage) is intended to run asynchronous code and shouldn't
// block. Otherwise it would temporarily stop processing of messages
// from other clients.
// Maybe call this method on another thread.
// Note that when this method is called, the RemoteEndpoint.Async
// is still in the process of sending data, so there probably should
// be another way to abort the Websocket connection.
// Ideally, there should be some abort() method that cancels the
// connection immediately...
session.close(cr);
} catch (IOException e) {
// Ignore
}
} else {
// to reduce TCP overhead (using ";" as separator).
if (msg instanceof StringWebsocketMessage && !messagesToSend.isEmpty() && messagesToSend.getLast() instanceof StringWebsocketMessage) {
StringWebsocketMessage ms = (StringWebsocketMessage) messagesToSend.removeLast();
messagesToSendLength -= calculateMessageLength(ms);
String concatenated = ms.getString() + ";" + ((StringWebsocketMessage) msg).getString();
msg = new StringWebsocketMessage(concatenated);
}
messagesToSend.add(msg);
messagesToSendLength += calculateMessageLength(msg);
}
} else {
isSendingMessage = true;
internalSendMessageAsync(msg);
}
}
}
}
use of javax.websocket.CloseReason in project knox by apache.
the class ProxyInboundClientTest method testTextMaxBufferLimit.
@Test(timeout = 3000)
public void testTextMaxBufferLimit() throws IOException, DeploymentException {
final String longMessage = RandomStringUtils.random(100000);
final AtomicBoolean isTestComplete = new AtomicBoolean(false);
final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
final ProxyInboundClient client = new ProxyInboundClient(new MessageEventCallback() {
/**
* A generic callback, can be left un-implemented
*
* @param message
*/
@Override
public void doCallback(String message) {
}
/**
* Callback when connection is established.
*
* @param session
*/
@Override
public void onConnectionOpen(Object session) {
}
/**
* Callback when connection is closed.
*
* @param reason
*/
@Override
public void onConnectionClose(CloseReason reason) {
isTestComplete.set(true);
}
/**
* Callback when there is an error in connection.
*
* @param cause
*/
@Override
public void onError(Throwable cause) {
isTestComplete.set(true);
}
/**
* Callback when a text message is received.
*
* @param message
* @param session
*/
@Override
public void onMessageText(String message, Object session) {
recievedMessage = message;
isTestComplete.set(true);
}
/**
* Callback when a binary message is received.
*
* @param message
* @param last
* @param session
*/
@Override
public void onMessageBinary(byte[] message, boolean last, Object session) {
}
});
Assert.assertThat(client, instanceOf(javax.websocket.Endpoint.class));
Session session = container.connectToServer(client, serverUri);
session.getBasicRemote().sendText(longMessage);
while (!isTestComplete.get()) {
/* just wait for the test to finish */
}
Assert.assertEquals(longMessage, recievedMessage);
}
use of javax.websocket.CloseReason in project tomee by apache.
the class WebSocketResourceTest method sayHi.
@Test
public void sayHi() throws Exception {
final URI uri = url.toURI();
final AtomicReference<String> message = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
Endpoint endpoint = new Endpoint() {
@Override
public void onClose(final Session session, final CloseReason closeReason) {
super.onClose(session, closeReason);
System.out.println("onClose: " + closeReason);
}
@Override
public void onError(final Session session, final Throwable throwable) {
super.onError(session, throwable);
System.out.println("onError: " + throwable);
}
@Override
public void onOpen(final Session session, final EndpointConfig endpointConfig) {
session.addMessageHandler(new Whole<String>() {
@Override
public void onMessage(final String content) {
message.set(content);
latch.countDown();
}
});
}
};
ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
public void beforeRequest(Map<String, List<String>> headers) {
headers.put("Authorization", asList("Basic " + printBase64Binary("tomee:tomee".getBytes())));
}
};
ClientEndpointConfig authorizationConfiguration = ClientEndpointConfig.Builder.create().configurator(configurator).build();
// use same keystore as the server
authorizationConfiguration.getUserProperties().put("org.apache.tomcat.websocket.SSL_TRUSTSTORE", "src/main/conf/keystore.jks");
authorizationConfiguration.getUserProperties().put("org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD", "123456");
Session session = ContainerProvider.getWebSocketContainer().connectToServer(endpoint, authorizationConfiguration, // null, null)
new URI("wss", uri.getUserInfo(), "localhost", PORT, "/example/socket", null, null));
latch.await(1, TimeUnit.MINUTES);
session.close();
assertEquals("Hello tomee", message.get());
}
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 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(() -> {
try {
executor.submit(new SendRunnable(session, thread, executor));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
for (CountDownLatch future : latches) {
assertTrue(future.await(40, TimeUnit.SECONDS));
}
for (int t = 0; t < NUM_THREADS; ++t) {
for (int i = 0; i < NUM_REQUESTS; ++i) {
String msg = "t-" + t + "-m-" + i;
assertTrue(msg, StressEndpoint.MESSAGES.remove(msg));
}
}
assertEquals(0, StressEndpoint.MESSAGES.size());
}
Aggregations