When creating many instances of the java WebSocketClient, there is much that can be shared between multiple instances: buffer pools, thread pools and NIO selectors. Thus the client API has been updated to use a factory pattern, where the factory can hold the configuration and instances of the common infrastructure:
WebSocketClientFactory factory = new WebSocketClientFactory(); factory.setBufferSize(4096); factory.start();
Once the WebSocketClientFactory is started, WebSocketClient instances can be created and configured:
WebSocketClient client = factory.newWebSocketClient(); client.setMaxIdleTime(30000); client.setMaxTextMessageSize(1024); client.setProtocol("chat");
The WebSocketClient does not need to be started and the configuration set is copied to the connection instances as they are opened.
A websocket connection can be created from a WebSocketClient by calling open and passing the URI and the websocket instance that will handle the call backs (eg onOpen, onMessage etc.):
Future future = client.open(uri,mywebsocket); WebSocket.Connection connection = future.get(10,TimeUnit.SECONDS);
The open call returns a Future to the WebSocket.Connection. Like the NIO.2 API in JDK7, calling get with a timeout imposes a connect time on the connection attempt and the connection will be aborted if the get times out. If the connection is successful, the connection returned by the get is the same object passed to the WebSocket.onOpen(Connection) callback, so it may be access and used in either way.
The connection instance accessed via the onOpen callback or Future.get() is used to send messages and also to configure the connection:
connection.setMaxIdleTime(10000); connection.setMaxTextMessageSize(2*1024); connection.setMaxBinaryMessageSize(64*1024);
The maximum message sizes are used to control how large messages can grow when they are being aggregated from multiple websocket frames. Small max message sizes protect a server against DOS attack.