use of io.undertow.websockets.core.BufferedTextMessage in project undertow by undertow-io.
the class WebSocketExtensionBasicTestCase method testLongTextMessage.
@Test
public void testLongTextMessage() throws Exception {
XnioWorker client;
Xnio xnio = Xnio.getInstance(WebSocketExtensionBasicTestCase.class.getClassLoader());
client = xnio.createWorker(OptionMap.builder().set(Options.WORKER_IO_THREADS, 2).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 30).set(Options.WORKER_TASK_MAX_THREADS, 30).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
WebSocketProtocolHandshakeHandler handler = webSocketDebugHandler().addExtension(new PerMessageDeflateHandshake());
DebugExtensionsHeaderHandler debug = new DebugExtensionsHeaderHandler(handler);
DefaultServer.setRootHandler(path().addPrefixPath("/", debug));
final String SEC_WEBSOCKET_EXTENSIONS = "permessage-deflate; client_no_context_takeover; client_max_window_bits";
List<WebSocketExtension> extensionsList = WebSocketExtension.parse(SEC_WEBSOCKET_EXTENSIONS);
final WebSocketClientNegotiation negotiation = new WebSocketClientNegotiation(null, extensionsList);
Set<ExtensionHandshake> extensionHandshakes = new HashSet<>();
extensionHandshakes.add(new PerMessageDeflateHandshake(true));
final WebSocketChannel clientChannel = WebSocketClient.connect(client, null, DefaultServer.getBufferPool(), OptionMap.EMPTY, new URI(DefaultServer.getDefaultServerURL()), WebSocketVersion.V13, negotiation, extensionHandshakes).get();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<String> result = new AtomicReference<>();
clientChannel.getReceiveSetter().set(new AbstractReceiveListener() {
@Override
protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
String data = message.getData();
// WebSocketLogger.ROOT_LOGGER.info("onFullTextMessage() - Client - Received: " + data.getBytes().length + " bytes.");
result.set(data);
latch.countDown();
}
@Override
protected void onFullCloseMessage(WebSocketChannel channel, BufferedBinaryMessage message) throws IOException {
message.getData().close();
WebSocketLogger.ROOT_LOGGER.info("onFullCloseMessage");
}
@Override
protected void onError(WebSocketChannel channel, Throwable error) {
WebSocketLogger.ROOT_LOGGER.info("onError");
super.onError(channel, error);
error.printStackTrace();
latch.countDown();
}
});
clientChannel.resumeReceives();
int LONG_MSG = 125 * 1024;
StringBuilder longMsg = new StringBuilder(LONG_MSG);
for (int i = 0; i < LONG_MSG; i++) {
longMsg.append(Integer.toString(i).charAt(0));
}
WebSockets.sendTextBlocking(longMsg.toString(), clientChannel);
latch.await(300, TimeUnit.SECONDS);
Assert.assertEquals(longMsg.toString(), result.get());
clientChannel.sendClose();
stopWorker(client);
}
use of io.undertow.websockets.core.BufferedTextMessage in project undertow by undertow-io.
the class ChatServer method main.
public static void main(final String[] args) {
System.out.println("To see chat in action is to open two different browsers and point them at http://localhost:8080");
Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(path().addPrefixPath("/myapp", websocket(new WebSocketConnectionCallback() {
@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
channel.getReceiveSetter().set(new AbstractReceiveListener() {
@Override
protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
final String messageData = message.getData();
for (WebSocketChannel session : channel.getPeerConnections()) {
WebSockets.sendText(messageData, session, null);
}
}
});
channel.resumeReceives();
}
})).addPrefixPath("/", resource(new ClassPathResourceManager(ChatServer.class.getClassLoader(), ChatServer.class.getPackage())).addWelcomeFiles("index.html"))).build();
server.start();
}
use of io.undertow.websockets.core.BufferedTextMessage in project undertow by undertow-io.
the class FrameHandler method onText.
@Override
protected void onText(WebSocketChannel webSocketChannel, StreamSourceFrameChannel messageChannel) throws IOException {
if (session.isSessionClosed()) {
// to bad, the channel has already been closed
// we just ignore messages that are received after we have closed, as the endpoint is no longer in a valid state to deal with them
// this this should only happen if a message was on the wire when we called close()
messageChannel.close();
return;
}
final HandlerWrapper handler = getHandler(FrameType.TEXT);
if (handler != null && handler.isPartialHandler()) {
BufferedTextMessage data = new BufferedTextMessage(false);
data.read(messageChannel, new WebSocketCallback<BufferedTextMessage>() {
@Override
public void complete(WebSocketChannel channel, BufferedTextMessage context) {
invokeTextHandler(context, handler, context.isComplete());
}
@Override
public void onError(WebSocketChannel channel, BufferedTextMessage context, Throwable throwable) {
invokeOnError(throwable);
}
});
} else {
bufferFullMessage(messageChannel);
}
}
use of io.undertow.websockets.core.BufferedTextMessage in project actframework by actframework.
the class UndertowWebSocketConnectionHandler method handle.
@Override
public void handle(final ActionContext context) {
if (logger.isTraceEnabled()) {
logger.trace("handle websocket connection request to %s", context.req().url());
}
final UndertowRequest req = (UndertowRequest) context.req();
HttpServerExchange exchange = req.exchange();
try {
Handlers.websocket(new WebSocketConnectionCallback() {
@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
final WebSocketConnection connection = new UndertowWebSocketConnection(channel, context.session());
channel.setAttribute("act_conn", connection);
connectionManager.registerNewConnection(connection, context);
final WebSocketContext wsCtx = new WebSocketContext(req.url(), connection, connectionManager, context, connectionManager.app());
if (logger.isTraceEnabled()) {
logger.trace("websocket context[%s] created for %s", connection.sessionId(), context.req().url());
}
channel.getReceiveSetter().set(new AbstractReceiveListener() {
@Override
protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
WebSocketContext.current(wsCtx);
String payload = message.getData();
if (logger.isTraceEnabled()) {
logger.trace("websocket message received: %s", payload);
}
wsCtx.messageReceived(payload);
invoke(wsCtx);
}
@Override
protected void onClose(WebSocketChannel webSocketChannel, StreamSourceFrameChannel channel) throws IOException {
if (logger.isTraceEnabled()) {
logger.trace("websocket closed: ", connection.sessionId());
}
WebSocketContext.current(wsCtx);
super.onClose(webSocketChannel, channel);
connection.destroy();
context.app().eventBus().emit(new WebSocketCloseEvent(wsCtx));
}
});
channel.resumeReceives();
Act.eventBus().emit(new WebSocketConnectEvent(wsCtx));
}
}).handleRequest(exchange);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw ActErrorResult.of(e);
}
}
Aggregations