Class WebSocket
- java.lang.Object
-
- com.neovisionaries.ws.client.WebSocket
-
public class WebSocket extends java.lang.ObjectWebSocket.Create WebSocketFactory
WebSocketFactoryis a factory class that createsWebSocketinstances. The first step is to create aWebSocketFactoryinstance.// Create a WebSocketFactory instance. WebSocketFactory factory = new
WebSocketFactory();By default,
WebSocketFactoryusesSocketFactory.getDefault()for non-secure WebSocket connections (ws:) andSSLSocketFactory.getDefault()for secure WebSocket connections (wss:). You can change this default behavior by usingWebSocketFactory.setSocketFactorymethod,WebSocketFactory.setSSLSocketFactorymethod andWebSocketFactory.setSSLContextmethod. Note that you don't have to call asetSSL*method at all if you use the default SSL configuration. Also note that callingsetSSLSocketFactorymethod has no meaning if you have calledsetSSLContextmethod. See the description ofWebSocketFactory.createSocket(URI)method for details.The following is an example to set a custom SSL context to a
WebSocketFactoryinstance. (Again, you don't have to call asetSSL*method if you use the default SSL configuration.)// Create a custom SSL context. SSLContext context = NaiveSSLContext.getInstance("TLS"); // Set the custom SSL context. factory.
setSSLContext(context); // Disable manual hostname verification for NaiveSSLContext. // // Manual hostname verification has been enabled since the // version 2.1. Because the verification is executed manually // after Socket.connect(SocketAddress, int) succeeds, the // hostname verification is always executed even if you has // passed an SSLContext which naively accepts any server // certificate. However, this behavior is not desirable in // some cases and you may want to disable the hostname // verification. You can disable the hostname verification // by calling WebSocketFactory.setVerifyHostname(false). factory.setVerifyHostname(false);NaiveSSLContext used in the above example is a factory class to create an
SSLContextwhich naively accepts all certificates without verification. It's enough for testing purposes. When you see an error message "unable to find valid certificate path to requested target" while testing, tryNaiveSSLContext.HTTP Proxy
If a WebSocket endpoint needs to be accessed via an HTTP proxy, information about the proxy server has to be set to a
WebSocketFactoryinstance before creating aWebSocketinstance. Proxy settings are represented byProxySettingsclass. AWebSocketFactoryinstance has an associatedProxySettingsinstance and it can be obtained by callingWebSocketFactory.getProxySettings()method.// Get the associated ProxySettings instance.
ProxySettingssettings = factory.getProxySettings();ProxySettingsclass has methods to set information about a proxy server such assetHostmethod andsetPortmethod. The following is an example to set a secure (https) proxy server.// Set a proxy server. settings.
setServer("https://proxy.example.com");If credentials are required for authentication at a proxy server,
setIdmethod andsetPasswordmethod, orsetCredentialsmethod can be used to set the credentials. Note that, however, the current implementation supports only Basic Authentication.// Set credentials for authentication at a proxy server. settings.
setCredentials(id, password);Create WebSocket
WebSocketclass represents a WebSocket. Its instances are created by calling one ofcreateSocketmethods of aWebSocketFactoryinstance. Below is the simplest example to create aWebSocketinstance.// Create a WebSocket. The scheme part can be one of the following: // 'ws', 'wss', 'http' and 'https' (case-insensitive). The user info // part, if any, is interpreted as expected. If a raw socket failed // to be created, an IOException is thrown. WebSocket ws = new
WebSocketFactory().createWebSocket("ws://localhost/endpoint");There are two ways to set a timeout value for socket connection. The first way is to call
setConnectionTimeout(int timeout)method ofWebSocketFactory.// Create a WebSocket factory and set 5000 milliseconds as a timeout // value for socket connection. WebSocketFactory factory = new WebSocketFactory().
setConnectionTimeout(5000); // Create a WebSocket. The timeout value set above is used. WebSocket ws = factory.createWebSocket("ws://localhost/endpoint");The other way is to give a timeout value to a
createSocketmethod.// Create a WebSocket factory. The timeout value remains 0. WebSocketFactory factory = new WebSocketFactory(); // Create a WebSocket with a socket connection timeout value. WebSocket ws = factory.
createWebSocket("ws://localhost/endpoint", 5000);The timeout value is passed to
connect(SocketAddress, int)method ofSocket.Register Listener
After creating a
WebSocketinstance, you should calladdListener(WebSocketListener)method to register aWebSocketListenerthat receives WebSocket events.WebSocketAdapteris an empty implementation ofWebSocketListenerinterface.// Register a listener to receive WebSocket events. ws.
addListener(newWebSocketAdapter(){@Override public voidonTextMessage(WebSocket websocket, String message) throws Exception { // Received a text message. ...... } });The table below is the list of callback methods defined in
WebSocketListenerinterface.WebSocketListenermethodsMethod Description handleCallbackErrorCalled when an onXxx()method threw aThrowable.onBinaryFrameCalled when a binary frame was received. onBinaryMessageCalled when a binary message was received. onCloseFrameCalled when a close frame was received. onConnectedCalled after the opening handshake succeeded. onConnectErrorCalled when connectAsynchronously()failed.onContinuationFrameCalled when a continuation frame was received. onDisconnectedCalled after a WebSocket connection was closed. onErrorCalled when an error occurred. onFrameCalled when a frame was received. onFrameErrorCalled when a frame failed to be read. onFrameSentCalled when a frame was sent. onFrameUnsentCalled when a frame was not sent. onMessageDecompressionErrorCalled when a message failed to be decompressed. onMessageErrorCalled when a message failed to be constructed. onPingFrameCalled when a ping frame was received. onPongFrameCalled when a pong frame was received. onSendErrorCalled when an error occurred on sending a frame. onSendingFrameCalled before a frame is sent. onSendingHandshakeCalled before an opening handshake is sent. onStateChangedCalled when the state of WebSocket changed. onTextFrameCalled when a text frame was received. onTextMessageCalled when a text message was received. onTextMessageErrorCalled when a text message failed to be constructed. onThreadCreatedCalled after a thread was created. onThreadStartedCalled at the beginning of a thread's run()method.onThreadStoppingCalled at the end of a thread's run()method.onUnexpectedErrorCalled when an uncaught throwable was detected. Configure WebSocket
Before starting a WebSocket opening handshake with the server, you can configure the
WebSocketinstance by using the following methods.Methods for Configuration METHOD DESCRIPTION addProtocolAdds an element to Sec-WebSocket-ProtocoladdExtensionAdds an element to Sec-WebSocket-ExtensionsaddHeaderAdds an arbitrary HTTP header. setUserInfoAdds Authorizationheader for Basic Authentication.getSocketGets the underlying Socketinstance to configure it. Note that this may returnnullsince version 2.9. Consider usinggetConnectedSocket()as necessary.getConnectedSocketEstablishes and gets the underlying Socket instance to configure it. Available since version 2.9. setExtendedDisables validity checks on RSV1/RSV2/RSV3 and opcode. setFrameQueueSizeSet the size of the frame queue for congestion control. setMaxPayloadSizeSet the maximum payload size. setMissingCloseFrameAllowedSet whether to allow the server to close the connection without sending a close frame. Connect To Server
By calling
connect()method, connection to the server is established and a WebSocket opening handshake is performed synchronously. If an error occurred during the handshake, aWebSocketExceptionwould be thrown. Instead, when the handshake succeeds, theconnect()implementation creates threads and starts them to read and write WebSocket frames asynchronously.try { // Connect to the server and perform an opening handshake. // This method blocks until the opening handshake is finished. ws.connect(); } catch (OpeningHandshakeExceptione) { // A violation against the WebSocket protocol was detected // during the opening handshake. } catch (HostnameUnverifiedExceptione) { // The certificate of the peer does not match the expected hostname. } catch (WebSocketExceptione) { // Failed to establish a WebSocket connection. }In some cases,
connect()method throwsOpeningHandshakeExceptionwhich is a subclass ofWebSocketException(since version 1.19).OpeningHandshakeExceptionprovides additional methods such asgetStatusLine(),getHeaders()andgetBody()to access the response from a server. The following snippet is an example to print information that the exception holds.catch (
OpeningHandshakeExceptione) { // Status line.StatusLinesl = e.getStatusLine(); System.out.println("=== Status Line ==="); System.out.format("HTTP Version = %s\n", sl.getHttpVersion()); System.out.format("Status Code = %d\n", sl.getStatusCode()); System.out.format("Reason Phrase = %s\n", sl.getReasonPhrase()); // HTTP headers. Map<String, List<String>> headers = e.getHeaders(); System.out.println("=== HTTP Headers ==="); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { // Header name. String name = entry.getKey(); // Values of the header. List<String> values = entry.getValue(); if (values == null || values.size() == 0) { // Print the name only. System.out.println(name); continue; } for (String value : values) { // Print the name and the value. System.out.format("%s: %s\n", name, value); } } }Also,
connect()method throwsHostnameUnverifiedExceptionwhich is a subclass ofWebSocketException(since version 2.1) when the certificate of the peer does not match the expected hostname.Connect To Server Asynchronously
The simplest way to call
connect()method asynchronously is to useconnectAsynchronously()method. The implementation of the method creates a thread and callsconnect()method in the thread. When theconnect()call failed,onConnectError()ofWebSocketListenerwould be called. Note thatonConnectError()is called only whenconnectAsynchronously()was used and theconnect()call executed in the background thread failed. Neither direct synchronousconnect()norconnect(ExecutorService)(described below) will trigger the callback method.// Connect to the server asynchronously. ws.
connectAsynchronously();Another way to call
connect()method asynchronously is to useconnect(ExecutorService)method. The method performs a WebSocket opening handshake asynchronously using the givenExecutorService.// Prepare an ExecutorService.
ExecutorServicees =Executors.newSingleThreadExecutor(); // Connect to the server asynchronously.Future<WebSocket>future = ws.connect(es); try { // Wait for the opening handshake to complete. future.get(); } catch (ExecutionExceptione) { if (e.getCause() instanceofWebSocketException) { ...... } }The implementation of
connect(ExecutorService)method creates aCallable<WebSocket>instance by callingconnectable()method and passes the instance tosubmit(Callable)method of the givenExecutorService. What the implementation ofcall()method of theCallableinstance does is just to call the synchronousconnect().Send Frames
WebSocket frames can be sent by
sendFrame(WebSocketFrame)method. OthersendXxxmethods such assendText(String)are aliases ofsendFramemethod. All of thesendXxxmethods work asynchronously. However, under some conditions,sendXxxmethods may block. See Congestion Control for details.Below are some examples of
sendXxxmethods. Note that in normal cases, you don't have to callsendClose()method andsendPong()(or their variants) explicitly because they are called automatically when appropriate.// Send a text frame. ws.
sendText("Hello."); // Send a binary frame. byte[] binary = ......; ws.sendBinary(binary); // Send a ping frame. ws.sendPing("Are you there?");If you want to send fragmented frames, you have to know the details of the specification (5.4. Fragmentation). Below is an example to send a text message (
"How are you?") which consists of 3 fragmented frames.// The first frame must be either a text frame or a binary frame. // And its FIN bit must be cleared. WebSocketFrame firstFrame = WebSocketFrame .
createTextFrame("How ") .setFin(false); // Subsequent frames must be continuation frames. The FIN bit of // all continuation frames except the last one must be cleared. // Note that the FIN bit of frames returned from // WebSocketFrame.createContinuationFrame methods is cleared, so // the example below does not clear the FIN bit explicitly. WebSocketFrame secondFrame = WebSocketFrame .createContinuationFrame("are "); // The last frame must be a continuation frame with the FIN bit set. // Note that the FIN bit of frames returned from // WebSocketFrame.createContinuationFrame methods is cleared, so // the FIN bit of the last frame must be set explicitly. WebSocketFrame lastFrame = WebSocketFrame .createContinuationFrame("you?") .setFin(true); // Send a text message which consists of 3 frames. ws.sendFrame(firstFrame) .sendFrame(secondFrame) .sendFrame(lastFrame);Alternatively, the same as above can be done like this.
// Send a text message which consists of 3 frames. ws.
sendText("How ", false) .sendContinuation("are ") .sendContinuation("you?", true);Send Ping/Pong Frames Periodically
You can send ping frames periodically by calling
setPingIntervalmethod with an interval in milliseconds between ping frames. This method can be called both before and afterconnect()method. Passing zero stops the periodical sending.// Send a ping per 60 seconds. ws.
setPingInterval(60 * 1000); // Stop the periodical sending. ws.setPingInterval(0);Likewise, you can send pong frames periodically by calling
setPongIntervalmethod. "A Pong frame MAY be sent unsolicited." (RFC 6455, 5.5.3. Pong)You can customize payload of ping/pong frames that are sent automatically by using
setPingPayloadGenerator(PayloadGenerator)andsetPongPayloadGenerator(PayloadGenerator)methods. Both methods take an instance ofPayloadGeneratorinterface. The following is an example to use the string representation of the current date as payload of ping frames.ws.
setPingPayloadGenerator(newPayloadGenerator() {@Override public byte[] generate() { // The string representation of the current date. return new Date().toString().getBytes(); } });Note that the maximum payload length of control frames (e.g. ping frames) is 125. Therefore, the length of a byte array returned from
generate()method must not exceed 125.You can change the names of the
Timers that send ping/pong frames periodically by usingsetPingSenderName(String)andsetPongSenderName(String)methods.// Change the Timers' names. ws.
setPingSenderName("PING_SENDER"); ws.setPongSenderName("PONG_SENDER");Auto Flush
By default, a frame is automatically flushed to the server immediately after
sendFramemethod is executed. This automatic flush can be disabled by callingsetAutoFlush(false).// Disable auto-flush. ws.
setAutoFlush(false);To flush frames manually, call
flush()method. Note that this method works asynchronously.// Flush frames to the server manually. ws.
flush();Congestion Control
sendXxxmethods queue aWebSocketFrameinstance to the internal queue. By default, no upper limit is imposed on the queue size, sosendXxxmethods do not block. However, this behavior may cause a problem if your WebSocket client application sends too many WebSocket frames in a short time for the WebSocket server to process. In such a case, you may wantsendXxxmethods to block when many frames are queued.You can set an upper limit on the internal queue by calling
setFrameQueueSize(int)method. As a result, if the number of frames in the queue has reached the upper limit when asendXxxmethod is called, the method blocks until the queue gets spaces. The code snippet below is an example to set 5 as the upper limit of the internal frame queue.// Set 5 as the frame queue size. ws.
setFrameQueueSize(5);Note that under some conditions, even if the queue is full,
sendXxxmethods do not block. For example, in the case where the thread to send frames (WritingThread) is going to stop or has already stopped. In addition, method calls to send a control frame (e.g.sendClose()andsendPing()) do not block.Maximum Payload Size
You can set an upper limit on the payload size of WebSocket frames by calling
setMaxPayloadSize(int)method with a positive value. Text, binary and continuation frames whose payload size is bigger than the maximum payload size you have set will be split into multiple frames.// Set 1024 as the maximum payload size. ws.
setMaxPayloadSize(1024);Control frames (close, ping and pong frames) are never split as per the specification.
If permessage-deflate extension is enabled and if the payload size of a WebSocket frame after compression does not exceed the maximum payload size, the WebSocket frame is not split even if the payload size before compression execeeds the maximum payload size.
Compression
The permessage-deflate extension (RFC 7692) has been supported since the version 1.17. To enable the extension, call
addExtensionmethod with"permessage-deflate".// Enable "permessage-deflate" extension (RFC 7692). ws.
addExtension(WebSocketExtension.PERMESSAGE_DEFLATE);Missing Close Frame
Some server implementations close a WebSocket connection without sending a close frame to a client in some cases. Strictly speaking, this is a violation against the specification (RFC 6455). However, this library has allowed the behavior by default since the version 1.29. Even if the end of the input stream of a WebSocket connection were reached without a close frame being received, it would trigger neither
onError()method noronFrameError()method ofWebSocketListener. If you want to make aWebSocketinstance report an error in the case, passfalsetosetMissingCloseFrameAllowed(boolean)method.// Make this library report an error when the end of the input stream // of the WebSocket connection is reached before a close frame is read. ws.
setMissingCloseFrameAllowed(false);Direct Text Message
When a text message was received,
onTextMessage(WebSocket, String)is called. The implementation internally converts the byte array of the text message into aStringobject before calling the listener method. If you want to receive the byte array directly without the string conversion, callsetDirectTextMessage(boolean)withtrue, andonTextMessage(WebSocket, byte[])will be called instead.// Receive text messages without string conversion. ws.
setDirectTextMessage(true);Disconnect WebSocket
Before a WebSocket is closed, a closing handshake is performed. A closing handshake is started (1) when the server sends a close frame to the client or (2) when the client sends a close frame to the server. You can start a closing handshake by calling
disconnect()method (or by sending a close frame manually).// Close the WebSocket connection. ws.
disconnect();disconnect()method has some variants. If you want to change the close code and the reason phrase of the close frame that this client will send to the server, use a variant method such asdisconnect(int, String).disconnect()method itself is an alias ofdisconnect(WebSocketCloseCode.NORMAL, null).Reconnection
connect()method can be called at most only once regardless of whether the method succeeded or failed. If you want to re-connect to the WebSocket endpoint, you have to create a newWebSocketinstance again by calling one ofcreateSocketmethods of aWebSocketFactory. You may findrecreate()method useful if you want to create a newWebSocketinstance that has the same settings as the original instance. Note that, however, settings you made on the raw socket of the originalWebSocketinstance are not copied.// Create a new WebSocket instance and connect to the same endpoint. ws = ws.
recreate().connect();There is a variant of
recreate()method that takes a timeout value for socket connection. If you want to use a timeout value that is different from the one used when the existingWebSocketinstance was created, userecreate(int timeout)method.Note that you should not trigger reconnection in
onError()method becauseonError()may be called multiple times due to one error. Instead,onDisconnected()is the right place to trigger reconnection.Also note that the reason I use an expression of "to trigger reconnection" instead of "to call
recreate().connect()" is that I myself won't do it synchronously inWebSocketListenercallback methods but will just schedule reconnection or will just go to the top of a kind of application loop that repeats to establish a WebSocket connection until it succeeds.Error Handling
WebSocketListenerhas someonXxxError()methods such asonFrameError()andonSendError(). Among such methods,onError()is a special one. It is always called before any otheronXxxError()is called. For example, in the implementation ofrun()method ofReadingThread,Throwableis caught andonError()andonUnexpectedError()are called in this order. The following is the implementation.@Override public void run() { try { main(); } catch (Throwable t) { // An uncaught throwable was detected in the reading thread.WebSocketExceptioncause = new WebSocketException(WebSocketError.UNEXPECTED_ERROR_IN_READING_THREAD, "An uncaught throwable was detected in the reading thread", t); // Notify the listeners. ListenerManager manager = mWebSocket.getListenerManager(); manager.callOnError(cause); manager.callOnUnexpectedError(cause); } }So, you can handle all error cases in
onError()method. However, note thatonError()may be called multiple times for one error cause, so don't try to trigger reconnection inonError(). Instead,onDiconnected()is the right place to trigger reconnection.All
onXxxError()methods receive aWebSocketExceptioninstance as the second argument (the first argument is aWebSocketinstance). The exception class providesgetError()method which returns aWebSocketErrorenum entry. Entries inWebSocketErrorenum are possible causes of errors that may occur in the implementation of this library. The error causes are so granular that they can make it easy for you to find the root cause when an error occurs.Throwables thrown by implementations ofonXXX()callback methods are passed tohandleCallbackError()ofWebSocketListener.@Override public voidhandleCallbackError(WebSocket websocket, Throwable cause) throws Exception { // Throwables thrown by onXxx() callback methods come here. }Thread Callbacks
Some threads are created internally in the implementation of
WebSocket. Known threads are as follows.Internal Threads THREAD TYPE DESCRIPTION READING_THREADA thread which reads WebSocket frames from the server. WRITING_THREADA thread which sends WebSocket frames to the server. CONNECT_THREADA thread which calls connect()asynchronously.FINISH_THREADA thread which does finalization of a WebSocketinstance.The following callback methods of
WebSocketListenerare called according to the life cycle of the threads.Thread Callbacks METHOD DESCRIPTION onThreadCreated()Called after a thread was created. onThreadStarted()Called at the beginning of the thread's run()method.onThreadStopping()Called at the end of the thread's run()method.For example, if you want to change the name of the reading thread, implement
onThreadCreated()method like below.@Override public voidonThreadCreated(WebSocket websocket,ThreadTypetype, Thread thread) { if (type == ThreadType.READING_THREAD) { thread.setName("READING_THREAD"); } }
-
-
Field Summary
-
Constructor Summary
Constructors Constructor Description WebSocket(WebSocketFactory factory, boolean secure, java.lang.String userInfo, java.lang.String host, java.lang.String path, SocketConnector connector)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description WebSocketaddExtension(WebSocketExtension extension)Add a value forSec-WebSocket-Extension.WebSocketaddExtension(java.lang.String extension)Add a value forSec-WebSocket-Extension.WebSocketaddHeader(java.lang.String name, java.lang.String value)Add a pair of extra HTTP header.WebSocketaddListener(WebSocketListener listener)Add a listener to receive events on this WebSocket.WebSocketaddListeners(java.util.List<WebSocketListener> listeners)Add listeners.WebSocketaddProtocol(java.lang.String protocol)Add a value forSec-WebSocket-Protocol.private voidcallOnConnectedIfNotYet()CallWebSocketListener.onConnected(WebSocket, Map)method of the registered listeners if it has not been called yet.private voidchangeStateOnConnect()WebSocketclearExtensions()Remove all extensions fromSec-WebSocket-Extension.WebSocketclearHeaders()Clear all extra HTTP headers.WebSocketclearListeners()Remove all the listeners from this WebSocket.WebSocketclearProtocols()Remove all protocols fromSec-WebSocket-Protocol.WebSocketclearUserInfo()Clear the credentials to connect to the WebSocket endpoint.WebSocketconnect()Connect to the server, send an opening handshake to the server, receive the response and then start threads to communicate with the server.java.util.concurrent.Future<WebSocket>connect(java.util.concurrent.ExecutorService executorService)Executeconnect()asynchronously using the givenExecutorService.java.util.concurrent.Callable<WebSocket>connectable()WebSocketconnectAsynchronously()Executeconnect()asynchronously by creating a new thread and callingconnect()in the thread.WebSocketdisconnect()Disconnect the WebSocket.WebSocketdisconnect(int closeCode)Disconnect the WebSocket.WebSocketdisconnect(int closeCode, java.lang.String reason)Disconnect the WebSocket.WebSocketdisconnect(int closeCode, java.lang.String reason, long closeDelay)Disconnect the WebSocket.WebSocketdisconnect(java.lang.String reason)Disconnect the WebSocket.protected voidfinalize()private PerMessageCompressionExtensionfindAgreedPerMessageCompressionExtension()Find a per-message compression extension from among the agreed extensions.(package private) voidfinish()private voidfinishAsynchronously()Callfinish()from within a separate thread.WebSocketflush()Flush frames to the server.private static java.lang.StringgenerateWebSocketKey()Generate a value for Sec-WebSocket-Key.java.util.List<WebSocketExtension>getAgreedExtensions()Get the agreed extensions.java.lang.StringgetAgreedProtocol()Get the agreed protocol.java.net.SocketgetConnectedSocket()Get the raw socket which this WebSocket uses internally.intgetFrameQueueSize()Get the size of the frame queue.(package private) HandshakeBuildergetHandshakeBuilder()Get the handshake builder.(package private) WebSocketInputStreamgetInput()Get the input stream of the WebSocket connection.(package private) ListenerManagergetListenerManager()Get the manager that manages registered listeners.intgetMaxPayloadSize()Get the maximum payload size.(package private) WebSocketOutputStreamgetOutput()Get the output stream of the WebSocket connection.(package private) PerMessageCompressionExtensiongetPerMessageCompressionExtension()Get the PerMessageCompressionExtension in the agreed extensions.longgetPingInterval()Get the interval of periodical ping frames.PayloadGeneratorgetPingPayloadGenerator()Get the generator of payload of ping frames that are sent automatically.java.lang.StringgetPingSenderName()Get the name of theTimerthat sends ping frames periodically.longgetPongInterval()Get the interval of periodical pong frames.PayloadGeneratorgetPongPayloadGenerator()Get the generator of payload of pong frames that are sent automatically.java.lang.StringgetPongSenderName()Get the name of theTimerthat sends pong frames periodically.java.net.SocketgetSocket()Get the raw socket which this WebSocket uses internally if it has been established, yet.WebSocketStategetState()Get the current state of this WebSocket.(package private) StateManagergetStateManager()Get the manager that manages the state of thisWebSocketinstance.java.net.URIgetURI()Get the URI of the WebSocket endpoint.booleanisAutoFlush()Check if flush is performed automatically aftersendFrame(WebSocketFrame)is done.booleanisDirectTextMessage()Check if text messages are passed to listeners without string conversion.booleanisExtended()Check if extended use of WebSocket frames are allowed.private booleanisInState(WebSocketState state)Check if the current state is equal to the specified state.booleanisMissingCloseFrameAllowed()Check if this instance allows the server to close the WebSocket connection without sending a close frame to this client.booleanisOpen()Check if the current state of this WebSocket isOPEN.(package private) voidonReadingThreadFinished(WebSocketFrame closeFrame)Called by the reading thread as its last step.(package private) voidonReadingThreadStarted()Called by the reading thread as its first step.private voidonThreadsFinished()Called when both the reading thread and the writing thread have finished.private voidonThreadsStarted()Called when both the reading thread and the writing thread have started.(package private) voidonWritingThreadFinished(WebSocketFrame closeFrame)Called by the writing thread as its last step.(package private) voidonWritingThreadStarted()Called by the writing thread as its first step.private WebSocketInputStreamopenInputStream(java.net.Socket socket)Open the input stream of the WebSocket connection.private WebSocketOutputStreamopenOutputStream(java.net.Socket socket)Open the output stream of the WebSocket connection.private java.util.Map<java.lang.String,java.util.List<java.lang.String>>readHandshake(WebSocketInputStream input, java.lang.String key)Receive an opening handshake response from the WebSocket server.WebSocketrecreate()Create a newWebSocketinstance that has the same settings as this instance.WebSocketrecreate(int timeout)Create a newWebSocketinstance that has the same settings as this instance.WebSocketremoveExtension(WebSocketExtension extension)Remove an extension fromSec-WebSocket-Extension.WebSocketremoveExtensions(java.lang.String name)Remove extensions fromSec-WebSocket-Extensionby an extension name.WebSocketremoveHeaders(java.lang.String name)Remove pairs of extra HTTP headers.WebSocketremoveListener(WebSocketListener listener)Remove a listener from this WebSocket.WebSocketremoveListeners(java.util.List<WebSocketListener> listeners)Remove listeners.WebSocketremoveProtocol(java.lang.String protocol)Remove a protocol fromSec-WebSocket-Protocol.WebSocketsendBinary(byte[] message)Send a binary message to the server.WebSocketsendBinary(byte[] payload, boolean fin)Send a binary frame to the server.WebSocketsendClose()Send a close frame to the server.WebSocketsendClose(int closeCode)Send a close frame to the server.WebSocketsendClose(int closeCode, java.lang.String reason)Send a close frame to the server.WebSocketsendContinuation()Send a continuation frame to the server.WebSocketsendContinuation(boolean fin)Send a continuation frame to the server.WebSocketsendContinuation(byte[] payload)Send a continuation frame to the server.WebSocketsendContinuation(byte[] payload, boolean fin)Send a continuation frame to the server.WebSocketsendContinuation(java.lang.String payload)Send a continuation frame to the server.WebSocketsendContinuation(java.lang.String payload, boolean fin)Send a continuation frame to the server.WebSocketsendFrame(WebSocketFrame frame)Send a WebSocket frame to the server.WebSocketsendPing()Send a ping frame to the server.WebSocketsendPing(byte[] payload)Send a ping frame to the server.WebSocketsendPing(java.lang.String payload)Send a ping frame to the server.WebSocketsendPong()Send a pong frame to the server.WebSocketsendPong(byte[] payload)Send a pong frame to the server.WebSocketsendPong(java.lang.String payload)Send a pong frame to the server.WebSocketsendText(java.lang.String message)Send a text message to the server.WebSocketsendText(java.lang.String payload, boolean fin)Send a text frame to the server.(package private) voidsetAgreedExtensions(java.util.List<WebSocketExtension> extensions)Set the agreed extensions.(package private) voidsetAgreedProtocol(java.lang.String protocol)Set the agreed protocol.WebSocketsetAutoFlush(boolean auto)Enable or disable auto-flush of sent frames.WebSocketsetDirectTextMessage(boolean direct)Set whether to receive text messages directly as byte arrays without string conversion.WebSocketsetExtended(boolean extended)Allow or disallow extended use of WebSocket frames.WebSocketsetFrameQueueSize(int size)Set the size of the frame queue.WebSocketsetMaxPayloadSize(int size)Set the maximum payload size.WebSocketsetMissingCloseFrameAllowed(boolean allowed)Set whether to allow the server to close the WebSocket connection without sending a close frame to this client.WebSocketsetPingInterval(long interval)Set the interval of periodical ping frames.WebSocketsetPingPayloadGenerator(PayloadGenerator generator)Set the generator of payload of ping frames that are sent automatically.WebSocketsetPingSenderName(java.lang.String name)Set the name of theTimerthat sends ping frames periodically.WebSocketsetPongInterval(long interval)Set the interval of periodical pong frames.WebSocketsetPongPayloadGenerator(PayloadGenerator generator)Set the generator of payload of pong frames that are sent automatically.WebSocketsetPongSenderName(java.lang.String name)Set the name of theTimerthat sends pong frames periodically.WebSocketsetUserInfo(java.lang.String userInfo)Set the credentials to connect to the WebSocket endpoint.WebSocketsetUserInfo(java.lang.String id, java.lang.String password)Set the credentials to connect to the WebSocket endpoint.private java.util.Map<java.lang.String,java.util.List<java.lang.String>>shakeHands(java.net.Socket socket)Perform the opening handshake.private java.util.List<WebSocketFrame>splitIfNecessary(WebSocketFrame frame)private voidstartThreads()Start both the reading thread and the writing thread.private voidstopThreads(long closeDelay)Stop both the reading thread and the writing thread.private voidwriteHandshake(WebSocketOutputStream output, java.lang.String key)Send an opening handshake request to the WebSocket server.
-
-
-
Field Detail
-
DEFAULT_CLOSE_DELAY
private static final long DEFAULT_CLOSE_DELAY
- See Also:
- Constant Field Values
-
mWebSocketFactory
private final WebSocketFactory mWebSocketFactory
-
mSocketConnector
private final SocketConnector mSocketConnector
-
mStateManager
private final StateManager mStateManager
-
mHandshakeBuilder
private HandshakeBuilder mHandshakeBuilder
-
mListenerManager
private final ListenerManager mListenerManager
-
mPingSender
private final PingSender mPingSender
-
mPongSender
private final PongSender mPongSender
-
mThreadsLock
private final java.lang.Object mThreadsLock
-
mInput
private WebSocketInputStream mInput
-
mOutput
private WebSocketOutputStream mOutput
-
mReadingThread
private ReadingThread mReadingThread
-
mWritingThread
private WritingThread mWritingThread
-
mServerHeaders
private java.util.Map<java.lang.String,java.util.List<java.lang.String>> mServerHeaders
-
mAgreedExtensions
private java.util.List<WebSocketExtension> mAgreedExtensions
-
mAgreedProtocol
private java.lang.String mAgreedProtocol
-
mExtended
private boolean mExtended
-
mAutoFlush
private boolean mAutoFlush
-
mMissingCloseFrameAllowed
private boolean mMissingCloseFrameAllowed
-
mDirectTextMessage
private boolean mDirectTextMessage
-
mFrameQueueSize
private int mFrameQueueSize
-
mMaxPayloadSize
private int mMaxPayloadSize
-
mOnConnectedCalled
private boolean mOnConnectedCalled
-
mOnConnectedCalledLock
private java.lang.Object mOnConnectedCalledLock
-
mReadingThreadStarted
private boolean mReadingThreadStarted
-
mWritingThreadStarted
private boolean mWritingThreadStarted
-
mReadingThreadFinished
private boolean mReadingThreadFinished
-
mWritingThreadFinished
private boolean mWritingThreadFinished
-
mServerCloseFrame
private WebSocketFrame mServerCloseFrame
-
mClientCloseFrame
private WebSocketFrame mClientCloseFrame
-
mPerMessageCompressionExtension
private PerMessageCompressionExtension mPerMessageCompressionExtension
-
-
Constructor Detail
-
WebSocket
WebSocket(WebSocketFactory factory, boolean secure, java.lang.String userInfo, java.lang.String host, java.lang.String path, SocketConnector connector)
-
-
Method Detail
-
recreate
public WebSocket recreate() throws java.io.IOException
Create a newWebSocketinstance that has the same settings as this instance. Note that, however, settings you made on the raw socket are not copied.The
WebSocketFactoryinstance that you used to create thisWebSocketinstance is used again.This method calls
recreate(int)with the timeout value that was used when this instance was created. If you want to create a socket connection with a different timeout value, userecreate(int)method instead.- Returns:
- A new
WebSocketinstance. - Throws:
java.io.IOException-WebSocketFactory.createSocket(URI)threw an exception.- Since:
- 1.6
-
recreate
public WebSocket recreate(int timeout) throws java.io.IOException
Create a newWebSocketinstance that has the same settings as this instance. Note that, however, settings you made on the raw socket are not copied.The
WebSocketFactoryinstance that you used to create thisWebSocketinstance is used again.- Parameters:
timeout- The timeout value in milliseconds for socket timeout. A timeout of zero is interpreted as an infinite timeout.- Returns:
- A new
WebSocketinstance. - Throws:
java.lang.IllegalArgumentException- The given timeout value is negative.java.io.IOException-WebSocketFactory.createSocket(URI)threw an exception.- Since:
- 1.10
-
finalize
protected void finalize() throws java.lang.Throwable- Overrides:
finalizein classjava.lang.Object- Throws:
java.lang.Throwable
-
getState
public WebSocketState getState()
Get the current state of this WebSocket.The initial state is
CREATED. Whenconnect()is called, the state is changed toCONNECTING, and then toOPENafter a successful opening handshake. The state is changed toCLOSINGwhen a closing handshake is started, and then toCLOSEDwhen the closing handshake finished.See the description of
WebSocketStatefor details.- Returns:
- The current state.
- See Also:
WebSocketState
-
isOpen
public boolean isOpen()
Check if the current state of this WebSocket isOPEN.- Returns:
trueif the current state is OPEN.- Since:
- 1.1
-
isInState
private boolean isInState(WebSocketState state)
Check if the current state is equal to the specified state.
-
addProtocol
public WebSocket addProtocol(java.lang.String protocol)
Add a value forSec-WebSocket-Protocol.- Parameters:
protocol- A protocol name.- Returns:
thisobject.- Throws:
java.lang.IllegalArgumentException- The protocol name is invalid. A protocol name must be a non-empty string with characters in the range U+0021 to U+007E not including separator characters.
-
removeProtocol
public WebSocket removeProtocol(java.lang.String protocol)
Remove a protocol fromSec-WebSocket-Protocol.- Parameters:
protocol- A protocol name.nullis silently ignored.- Returns:
thisobject.- Since:
- 1.14
-
clearProtocols
public WebSocket clearProtocols()
Remove all protocols fromSec-WebSocket-Protocol.- Returns:
thisobject.- Since:
- 1.14
-
addExtension
public WebSocket addExtension(WebSocketExtension extension)
Add a value forSec-WebSocket-Extension.- Parameters:
extension- An extension.nullis silently ignored.- Returns:
thisobject.
-
addExtension
public WebSocket addExtension(java.lang.String extension)
Add a value forSec-WebSocket-Extension. The input string should comply with the format described in 9.1. Negotiating Extensions in RFC 6455.- Parameters:
extension- A string that represents a WebSocket extension. If it does not comply with RFC 6455, no value is added toSec-WebSocket-Extension.- Returns:
thisobject.- Since:
- 1.14
-
removeExtension
public WebSocket removeExtension(WebSocketExtension extension)
Remove an extension fromSec-WebSocket-Extension.- Parameters:
extension- An extension to remove.nullis silently ignored.- Returns:
thisobject.- Since:
- 1.14
-
removeExtensions
public WebSocket removeExtensions(java.lang.String name)
Remove extensions fromSec-WebSocket-Extensionby an extension name.- Parameters:
name- An extension name.nullis silently ignored.- Returns:
thisobject.- Since:
- 1.14
-
clearExtensions
public WebSocket clearExtensions()
Remove all extensions fromSec-WebSocket-Extension.- Returns:
thisobject.- Since:
- 1.14
-
addHeader
public WebSocket addHeader(java.lang.String name, java.lang.String value)
Add a pair of extra HTTP header.- Parameters:
name- An HTTP header name. Whennullor an empty string is given, no header is added.value- The value of the HTTP header.- Returns:
thisobject.
-
removeHeaders
public WebSocket removeHeaders(java.lang.String name)
Remove pairs of extra HTTP headers.- Parameters:
name- An HTTP header name.nullis silently ignored.- Returns:
thisobject.- Since:
- 1.14
-
clearHeaders
public WebSocket clearHeaders()
Clear all extra HTTP headers.- Returns:
thisobject.- Since:
- 1.14
-
setUserInfo
public WebSocket setUserInfo(java.lang.String userInfo)
Set the credentials to connect to the WebSocket endpoint.- Parameters:
userInfo- The credentials for Basic Authentication. The format should beid:password.- Returns:
thisobject.
-
setUserInfo
public WebSocket setUserInfo(java.lang.String id, java.lang.String password)
Set the credentials to connect to the WebSocket endpoint.- Parameters:
id- The ID.password- The password.- Returns:
thisobject.
-
clearUserInfo
public WebSocket clearUserInfo()
Clear the credentials to connect to the WebSocket endpoint.- Returns:
thisobject.- Since:
- 1.14
-
isExtended
public boolean isExtended()
Check if extended use of WebSocket frames are allowed.When extended use is allowed, values of RSV1/RSV2/RSV3 bits and opcode of frames are not checked. On the other hand, if not allowed (default), non-zero values for RSV1/RSV2/RSV3 bits and unknown opcodes cause an error. In such a case,
onFrameErrormethod of listeners are called and the WebSocket is eventually closed.- Returns:
trueif extended use of WebSocket frames are allowed.
-
setExtended
public WebSocket setExtended(boolean extended)
Allow or disallow extended use of WebSocket frames.- Parameters:
extended-trueto allow extended use of WebSocket frames.- Returns:
thisobject.
-
isAutoFlush
public boolean isAutoFlush()
Check if flush is performed automatically aftersendFrame(WebSocketFrame)is done. The default value istrue.- Returns:
trueif flush is performed automatically.- Since:
- 1.5
-
setAutoFlush
public WebSocket setAutoFlush(boolean auto)
Enable or disable auto-flush of sent frames.- Parameters:
auto-trueto enable auto-flush.falseto disable it.- Returns:
thisobject.- Since:
- 1.5
-
isMissingCloseFrameAllowed
public boolean isMissingCloseFrameAllowed()
Check if this instance allows the server to close the WebSocket connection without sending a close frame to this client. The default value istrue.- Returns:
trueif the configuration allows for the server to close the WebSocket connection without sending a close frame to this client.falseif the configuration requires that an error be reported viaonError()method andonFrameError()method ofWebSocketListener.- Since:
- 1.29
-
setMissingCloseFrameAllowed
public WebSocket setMissingCloseFrameAllowed(boolean allowed)
Set whether to allow the server to close the WebSocket connection without sending a close frame to this client.- Parameters:
allowed-trueto allow the server to close the WebSocket connection without sending a close frame to this client.falseto make this instance report an error when the end of the input stream of the WebSocket connection is reached before a close frame is read.- Returns:
thisobject.- Since:
- 1.29
-
isDirectTextMessage
public boolean isDirectTextMessage()
Check if text messages are passed to listeners without string conversion.If this method returns
true, when a text message is received,onTextMessage(WebSocket, byte[])will be called instead ofonTextMessage(WebSocket, String). The purpose of this behavior is to skip internal string conversion which is performed in the implementation ofReadingThread.- Returns:
trueif text messages are passed to listeners without string conversion.- Since:
- 2.6
-
setDirectTextMessage
public WebSocket setDirectTextMessage(boolean direct)
Set whether to receive text messages directly as byte arrays without string conversion.If
trueis set to this property, when a text message is received,onTextMessage(WebSocket, byte[])will be called instead ofonTextMessage(WebSocket, String). The purpose of this behavior is to skip internal string conversion which is performed in the implementation ofReadingThread.- Parameters:
direct-trueto receive text messages as byte arrays.- Returns:
thisobject.- Since:
- 2.6
-
flush
public WebSocket flush()
Flush frames to the server. Flush is performed asynchronously.- Returns:
thisobject.- Since:
- 1.5
-
getFrameQueueSize
public int getFrameQueueSize()
Get the size of the frame queue. The default value is 0 and it means there is no limit on the queue size.- Returns:
- The size of the frame queue.
- Since:
- 1.15
-
setFrameQueueSize
public WebSocket setFrameQueueSize(int size) throws java.lang.IllegalArgumentException
Set the size of the frame queue. The default value is 0 and it means there is no limit on the queue size.sendXxxmethods queue aWebSocketFrameinstance to the internal queue. If the number of frames in the queue has reached the upper limit (which has been set by this method) when asendXxxmethod is called, the method blocks until the queue gets spaces.Under some conditions, even if the queue is full,
sendXxxmethods do not block. For example, in the case where the thread to send frames (WritingThread) is going to stop or has already stopped. In addition, method calls to send a control frame (e.g.sendClose()andsendPing()) do not block.- Parameters:
size- The queue size. 0 means no limit. Negative numbers are not allowed.- Returns:
thisobject.- Throws:
java.lang.IllegalArgumentException-sizeis negative.- Since:
- 1.15
-
getMaxPayloadSize
public int getMaxPayloadSize()
Get the maximum payload size. The default value is 0 which means that the maximum payload size is not set and as a result frames are not split.- Returns:
- The maximum payload size. 0 means that the maximum payload size is not set.
- Since:
- 1.27
-
setMaxPayloadSize
public WebSocket setMaxPayloadSize(int size) throws java.lang.IllegalArgumentException
Set the maximum payload size.Text, binary and continuation frames whose payload size is bigger than the maximum payload size will be split into multiple frames. Note that control frames (close, ping and pong frames) are not split as per the specification even if their payload size exceeds the maximum payload size.
- Parameters:
size- The maximum payload size. 0 to unset the maximum payload size.- Returns:
thisobject.- Throws:
java.lang.IllegalArgumentException-sizeis negative.- Since:
- 1.27
-
getPingInterval
public long getPingInterval()
Get the interval of periodical ping frames.- Returns:
- The interval in milliseconds.
- Since:
- 1.2
-
setPingInterval
public WebSocket setPingInterval(long interval)
Set the interval of periodical ping frames.Setting a positive number starts sending ping frames periodically. Setting zero stops the periodical sending. This method can be called both before and after
connect()method.- Parameters:
interval- The interval in milliseconds. A negative value is regarded as zero.- Returns:
thisobject.- Since:
- 1.2
-
getPongInterval
public long getPongInterval()
Get the interval of periodical pong frames.- Returns:
- The interval in milliseconds.
- Since:
- 1.2
-
setPongInterval
public WebSocket setPongInterval(long interval)
Set the interval of periodical pong frames.Setting a positive number starts sending pong frames periodically. Setting zero stops the periodical sending. This method can be called both before and after
connect()method.- An excerpt from RFC 6455, 5.5.3. Pong
-
A Pong frame MAY be sent unsolicited. This serves as a unidirectional heartbeat. A response to an unsolicited Pong frame is not expected.
- Parameters:
interval- The interval in milliseconds. A negative value is regarded as zero.- Returns:
thisobject.- Since:
- 1.2
-
getPingPayloadGenerator
public PayloadGenerator getPingPayloadGenerator()
Get the generator of payload of ping frames that are sent automatically.- Returns:
- The generator of payload ping frames that are sent automatically.
- Since:
- 1.20
-
setPingPayloadGenerator
public WebSocket setPingPayloadGenerator(PayloadGenerator generator)
Set the generator of payload of ping frames that are sent automatically.- Parameters:
generator- The generator of payload ping frames that are sent automatically.- Since:
- 1.20
-
getPongPayloadGenerator
public PayloadGenerator getPongPayloadGenerator()
Get the generator of payload of pong frames that are sent automatically.- Returns:
- The generator of payload pong frames that are sent automatically.
- Since:
- 1.20
-
setPongPayloadGenerator
public WebSocket setPongPayloadGenerator(PayloadGenerator generator)
Set the generator of payload of pong frames that are sent automatically.- Parameters:
generator- The generator of payload ppng frames that are sent automatically.- Since:
- 1.20
-
getPingSenderName
public java.lang.String getPingSenderName()
Get the name of theTimerthat sends ping frames periodically.- Returns:
- The
Timer's name. - Since:
- 2.5
-
setPingSenderName
public WebSocket setPingSenderName(java.lang.String name)
Set the name of theTimerthat sends ping frames periodically.- Parameters:
name- A name for theTimer.- Returns:
thisobject.- Since:
- 2.5
-
getPongSenderName
public java.lang.String getPongSenderName()
Get the name of theTimerthat sends pong frames periodically.- Returns:
- The
Timer's name. - Since:
- 2.5
-
setPongSenderName
public WebSocket setPongSenderName(java.lang.String name)
Set the name of theTimerthat sends pong frames periodically.- Parameters:
name- A name for theTimer.- Returns:
thisobject.- Since:
- 2.5
-
addListener
public WebSocket addListener(WebSocketListener listener)
Add a listener to receive events on this WebSocket.- Parameters:
listener- A listener to add.- Returns:
thisobject.
-
addListeners
public WebSocket addListeners(java.util.List<WebSocketListener> listeners)
Add listeners.- Parameters:
listeners- Listeners to add.nullis silently ignored.nullelements in the list are ignored, too.- Returns:
thisobject.- Since:
- 1.14
-
removeListener
public WebSocket removeListener(WebSocketListener listener)
Remove a listener from this WebSocket.- Parameters:
listener- A listener to remove.nullwon't cause an error.- Returns:
thisobject.- Since:
- 1.13
-
removeListeners
public WebSocket removeListeners(java.util.List<WebSocketListener> listeners)
Remove listeners.- Parameters:
listeners- Listeners to remove.nullis silently ignored.nullelements in the list are ignored, too.- Returns:
thisobject.- Since:
- 1.14
-
clearListeners
public WebSocket clearListeners()
Remove all the listeners from this WebSocket.- Returns:
thisobject.- Since:
- 1.13
-
getSocket
public java.net.Socket getSocket()
Get the raw socket which this WebSocket uses internally if it has been established, yet.Version 2.9 has changed the behavior of this method, and this method may return
nullif the underlying socket has not been established yet. Consider usinggetConnectedSocket()method as necessary.- Returns:
- The underlying
Socketinstance. This may benullin case the underlying socket has not been established, yet. - See Also:
getConnectedSocket()
-
getConnectedSocket
public java.net.Socket getConnectedSocket() throws WebSocketExceptionGet the raw socket which this WebSocket uses internally. This will establish a connection to the server if not already done.- Returns:
- The underlying
Socketinstance. - Throws:
WebSocketException- Since:
- 2.9
-
getURI
public java.net.URI getURI()
Get the URI of the WebSocket endpoint. The scheme part is either"ws"or"wss". The authority part is always empty.- Returns:
- The URI of the WebSocket endpoint.
- Since:
- 1.1
-
connect
public WebSocket connect() throws WebSocketException
Connect to the server, send an opening handshake to the server, receive the response and then start threads to communicate with the server.As necessary,
addProtocol(String),addExtension(WebSocketExtension)addHeader(String, String)should be called before you call this method. It is because the parameters set by these methods are used in the opening handshake.Also, as necessary,
getSocket()should be used to set up socket parameters before you call this method. For example, you can set the socket timeout like the following. Note that, however, because the version 2.9 changed the behavior ofgetSocket()and the method may returnnullif the underlying socket has not been established yet, you may need to usegetConnectedSocket()method instead.WebSocket websocket = ......; websocket.
getSocket().setSoTimeout(5000); // getConnectedSocket() instead of getSocket(), since version 2.9. websocket.getConnectedSocket().setSoTimeout(5000);If the WebSocket endpoint requires Basic Authentication, you can set credentials by
setUserInfo(userInfo)orsetUserInfo(id, password)before you call this method. Note that if the URI passed toWebSocketFactory.createSocketmethod contains the user-info part, you don't have to callsetUserInfomethod.Note that this method can be called at most only once regardless of whether this method succeeded or failed. If you want to re-connect to the WebSocket endpoint, you have to create a new
WebSocketinstance again by calling one ofcreateSocketmethods of aWebSocketFactory. You may findrecreate()method useful if you want to create a newWebSocketinstance that has the same settings as this instance. (But settings you made on the raw socket are not copied.)- Returns:
thisobject.- Throws:
WebSocketException-- The current state of the WebSocket is not
CREATED - Connecting the server failed.
- The opening handshake failed.
- The current state of the WebSocket is not
-
connect
public java.util.concurrent.Future<WebSocket> connect(java.util.concurrent.ExecutorService executorService)
Executeconnect()asynchronously using the givenExecutorService. This method is just an alias of the following.executorService.submit(connectable())- Parameters:
executorService- AnExecutorServiceto execute a task created byconnectable().- Returns:
- The value returned from
ExecutorService.submit(Callable). - Throws:
java.lang.NullPointerException- If the givenExecutorServiceisnull.java.util.concurrent.RejectedExecutionException- If the givenExecutorServicerejected the task created byconnectable().- Since:
- 1.7
- See Also:
connectAsynchronously()
-
connectable
public java.util.concurrent.Callable<WebSocket> connectable()
Get a newCallable<WebSocket>instance whosecall()method callsconnect()method of thisWebSocketinstance.- Returns:
- A new
Callable<WebSocket>instance for asynchronousconnect(). - Since:
- 1.7
- See Also:
connect(ExecutorService)
-
connectAsynchronously
public WebSocket connectAsynchronously()
Executeconnect()asynchronously by creating a new thread and callingconnect()in the thread. Ifconnect()failed,onConnectError()method ofWebSocketListeneris called.- Returns:
thisobject.- Since:
- 1.8
-
disconnect
public WebSocket disconnect()
Disconnect the WebSocket.This method is an alias of
disconnect(WebSocketCloseCode.NORMAL, null).- Returns:
thisobject.
-
disconnect
public WebSocket disconnect(int closeCode)
Disconnect the WebSocket.This method is an alias of
disconnect(closeCode, null).- Parameters:
closeCode- The close code embedded in a close frame which this WebSocket client will send to the server.- Returns:
thisobject.- Since:
- 1.5
-
disconnect
public WebSocket disconnect(java.lang.String reason)
Disconnect the WebSocket.This method is an alias of
disconnect(WebSocketCloseCode.NORMAL, reason).- Parameters:
reason- The reason embedded in a close frame which this WebSocket client will send to the server. Note that the length of the bytes which represents the given reason must not exceed 125. In other words,(reason.getBytes("UTF-8").length <= 125)must be true.- Returns:
thisobject.- Since:
- 1.5
-
disconnect
public WebSocket disconnect(int closeCode, java.lang.String reason)
Disconnect the WebSocket.This method is an alias of
disconnect(closeCode, reason, 10000L).- Parameters:
closeCode- The close code embedded in a close frame which this WebSocket client will send to the server.reason- The reason embedded in a close frame which this WebSocket client will send to the server. Note that the length of the bytes which represents the given reason must not exceed 125. In other words,(reason.getBytes("UTF-8").length <= 125)must be true.- Returns:
thisobject.- Since:
- 1.5
- See Also:
WebSocketCloseCode, RFC 6455, 5.5.1. Close
-
disconnect
public WebSocket disconnect(int closeCode, java.lang.String reason, long closeDelay)
Disconnect the WebSocket.- Parameters:
closeCode- The close code embedded in a close frame which this WebSocket client will send to the server.reason- The reason embedded in a close frame which this WebSocket client will send to the server. Note that the length of the bytes which represents the given reason must not exceed 125. In other words,(reason.getBytes("UTF-8").length <= 125)must be true.closeDelay- Delay in milliseconds before callingSocket.close()forcibly. This safeguard is needed for the case where the server fails to send back a close frame. The default value is 10000 (= 10 seconds). When a negative value is given, the default value is used. If a very short time (e.g. 0) is given, it is likely to happen either (1) that this client will fail to send a close frame to the server (in this case, you will probably see an error message "Flushing frames to the server failed: Socket closed") or (2) that the WebSocket connection will be closed before this client receives a close frame from the server (in this case, the second argument ofWebSocketListener.onDisconnectedwill benull).- Returns:
thisobject.- Since:
- 1.26
- See Also:
WebSocketCloseCode, RFC 6455, 5.5.1. Close
-
getAgreedExtensions
public java.util.List<WebSocketExtension> getAgreedExtensions()
Get the agreed extensions.This method works correctly only after
connect()succeeds (= after the opening handshake succeeds).- Returns:
- The agreed extensions.
-
getAgreedProtocol
public java.lang.String getAgreedProtocol()
Get the agreed protocol.This method works correctly only after
connect()succeeds (= after the opening handshake succeeds).- Returns:
- The agreed protocol.
-
sendFrame
public WebSocket sendFrame(WebSocketFrame frame)
Send a WebSocket frame to the server.This method just queues the given frame. Actual transmission is performed asynchronously.
When the current state of this WebSocket is not
OPEN, this method does not accept the frame.Sending a close frame changes the state to
CLOSING(if the current state is neitherCLOSINGnorCLOSED).Note that the validity of the give frame is not checked. For example, even if the payload length of a given frame is greater than 125 and the opcode indicates that the frame is a control frame, this method accepts the given frame.
- Parameters:
frame- A WebSocket frame to be sent to the server. Ifnullis given, nothing is done.- Returns:
thisobject.
-
splitIfNecessary
private java.util.List<WebSocketFrame> splitIfNecessary(WebSocketFrame frame)
-
sendContinuation
public WebSocket sendContinuation()
Send a continuation frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createContinuationFrame()).Note that the FIN bit of a frame sent by this method is
false. If you want to set the FIN bit, usesendContinuation(boolean fin)withfin=true.- Returns:
thisobject.
-
sendContinuation
public WebSocket sendContinuation(boolean fin)
Send a continuation frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createContinuationFrame().setFin(fin)).- Parameters:
fin- The FIN bit value.- Returns:
thisobject.
-
sendContinuation
public WebSocket sendContinuation(java.lang.String payload)
Send a continuation frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createContinuationFrame(payload)).Note that the FIN bit of a frame sent by this method is
false. If you want to set the FIN bit, usesendContinuation(String payload, boolean fin)withfin=true.- Parameters:
payload- The payload of a continuation frame.- Returns:
thisobject.
-
sendContinuation
public WebSocket sendContinuation(java.lang.String payload, boolean fin)
Send a continuation frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createContinuationFrame(payload).setFin(fin)).- Parameters:
payload- The payload of a continuation frame.fin- The FIN bit value.- Returns:
thisobject.
-
sendContinuation
public WebSocket sendContinuation(byte[] payload)
Send a continuation frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createContinuationFrame(payload)).Note that the FIN bit of a frame sent by this method is
false. If you want to set the FIN bit, usesendContinuation(byte[] payload, boolean fin)withfin=true.- Parameters:
payload- The payload of a continuation frame.- Returns:
thisobject.
-
sendContinuation
public WebSocket sendContinuation(byte[] payload, boolean fin)
Send a continuation frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createContinuationFrame(payload).setFin(fin)).- Parameters:
payload- The payload of a continuation frame.fin- The FIN bit value.- Returns:
thisobject.
-
sendText
public WebSocket sendText(java.lang.String message)
Send a text message to the server.This method is an alias of
sendFrame(WebSocketFrame.createTextFrame(message)).If you want to send a text frame that is to be followed by continuation frames, use
setText(String payload, boolean fin)withfin=false.- Parameters:
message- A text message to be sent to the server.- Returns:
thisobject.
-
sendText
public WebSocket sendText(java.lang.String payload, boolean fin)
Send a text frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createTextFrame(payload).setFin(fin)).- Parameters:
payload- The payload of a text frame.fin- The FIN bit value.- Returns:
thisobject.
-
sendBinary
public WebSocket sendBinary(byte[] message)
Send a binary message to the server.This method is an alias of
sendFrame(WebSocketFrame.createBinaryFrame(message)).If you want to send a binary frame that is to be followed by continuation frames, use
setBinary(byte[] payload, boolean fin)withfin=false.- Parameters:
message- A binary message to be sent to the server.- Returns:
thisobject.
-
sendBinary
public WebSocket sendBinary(byte[] payload, boolean fin)
Send a binary frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createBinaryFrame(payload).setFin(fin)).- Parameters:
payload- The payload of a binary frame.fin- The FIN bit value.- Returns:
thisobject.
-
sendClose
public WebSocket sendClose()
Send a close frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createCloseFrame()).- Returns:
thisobject.
-
sendClose
public WebSocket sendClose(int closeCode)
Send a close frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createCloseFrame(closeCode)).- Parameters:
closeCode- The close code.- Returns:
thisobject.- See Also:
WebSocketCloseCode
-
sendClose
public WebSocket sendClose(int closeCode, java.lang.String reason)
Send a close frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createCloseFrame(closeCode, reason)).- Parameters:
closeCode- The close code.reason- The close reason. Note that a control frame's payload length must be 125 bytes or less (RFC 6455, 5.5. Control Frames).- Returns:
thisobject.- See Also:
WebSocketCloseCode
-
sendPing
public WebSocket sendPing()
Send a ping frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createPingFrame()).- Returns:
thisobject.
-
sendPing
public WebSocket sendPing(byte[] payload)
Send a ping frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createPingFrame(payload)).- Parameters:
payload- The payload for a ping frame. Note that a control frame's payload length must be 125 bytes or less (RFC 6455, 5.5. Control Frames).- Returns:
thisobject.
-
sendPing
public WebSocket sendPing(java.lang.String payload)
Send a ping frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createPingFrame(payload)).- Parameters:
payload- The payload for a ping frame. Note that a control frame's payload length must be 125 bytes or less (RFC 6455, 5.5. Control Frames).- Returns:
thisobject.
-
sendPong
public WebSocket sendPong()
Send a pong frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createPongFrame()).- Returns:
thisobject.
-
sendPong
public WebSocket sendPong(byte[] payload)
Send a pong frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createPongFrame(payload)).- Parameters:
payload- The payload for a pong frame. Note that a control frame's payload length must be 125 bytes or less (RFC 6455, 5.5. Control Frames).- Returns:
thisobject.
-
sendPong
public WebSocket sendPong(java.lang.String payload)
Send a pong frame to the server.This method is an alias of
sendFrame(WebSocketFrame.createPongFrame(payload)).- Parameters:
payload- The payload for a pong frame. Note that a control frame's payload length must be 125 bytes or less (RFC 6455, 5.5. Control Frames).- Returns:
thisobject.
-
changeStateOnConnect
private void changeStateOnConnect() throws WebSocketException- Throws:
WebSocketException
-
shakeHands
private java.util.Map<java.lang.String,java.util.List<java.lang.String>> shakeHands(java.net.Socket socket) throws WebSocketExceptionPerform the opening handshake.- Throws:
WebSocketException
-
openInputStream
private WebSocketInputStream openInputStream(java.net.Socket socket) throws WebSocketException
Open the input stream of the WebSocket connection. The stream is used by the reading thread.- Throws:
WebSocketException
-
openOutputStream
private WebSocketOutputStream openOutputStream(java.net.Socket socket) throws WebSocketException
Open the output stream of the WebSocket connection. The stream is used by the writing thread.- Throws:
WebSocketException
-
generateWebSocketKey
private static java.lang.String generateWebSocketKey()
Generate a value for Sec-WebSocket-Key.The request MUST include a header field with the name Sec-WebSocket-Key. The value of this header field MUST be a nonce consisting of a randomly selected 16-byte value that has been base64-encoded (see Section 4 of RFC 4648). The nonce MUST be selected randomly for each connection.
- Returns:
- A randomly generated WebSocket key.
-
writeHandshake
private void writeHandshake(WebSocketOutputStream output, java.lang.String key) throws WebSocketException
Send an opening handshake request to the WebSocket server.- Throws:
WebSocketException
-
readHandshake
private java.util.Map<java.lang.String,java.util.List<java.lang.String>> readHandshake(WebSocketInputStream input, java.lang.String key) throws WebSocketException
Receive an opening handshake response from the WebSocket server.- Throws:
WebSocketException
-
startThreads
private void startThreads()
Start both the reading thread and the writing thread.The reading thread will call
onReadingThreadStarted()as its first step. Likewise, the writing thread will callonWritingThreadStarted()as its first step. After both the threads have started,onThreadsStarted()is called.
-
stopThreads
private void stopThreads(long closeDelay)
Stop both the reading thread and the writing thread.The reading thread will call
onReadingThreadFinished(WebSocketFrame)as its last step. Likewise, the writing thread will callonWritingThreadFinished(WebSocketFrame)as its last step. After both the threads have stopped,onThreadsFinished()is called.
-
getInput
WebSocketInputStream getInput()
Get the input stream of the WebSocket connection.
-
getOutput
WebSocketOutputStream getOutput()
Get the output stream of the WebSocket connection.
-
getStateManager
StateManager getStateManager()
Get the manager that manages the state of thisWebSocketinstance.
-
getListenerManager
ListenerManager getListenerManager()
Get the manager that manages registered listeners.
-
getHandshakeBuilder
HandshakeBuilder getHandshakeBuilder()
Get the handshake builder.HandshakeReaderuses this method.
-
setAgreedExtensions
void setAgreedExtensions(java.util.List<WebSocketExtension> extensions)
Set the agreed extensions.HandshakeReaderuses this method.
-
setAgreedProtocol
void setAgreedProtocol(java.lang.String protocol)
Set the agreed protocol.HandshakeReaderuses this method.
-
onReadingThreadStarted
void onReadingThreadStarted()
Called by the reading thread as its first step.
-
onWritingThreadStarted
void onWritingThreadStarted()
Called by the writing thread as its first step.
-
callOnConnectedIfNotYet
private void callOnConnectedIfNotYet()
CallWebSocketListener.onConnected(WebSocket, Map)method of the registered listeners if it has not been called yet. Either the reading thread or the writing thread calls this method.
-
onThreadsStarted
private void onThreadsStarted()
Called when both the reading thread and the writing thread have started. This method is called in the context of either the reading thread or the writing thread.
-
onReadingThreadFinished
void onReadingThreadFinished(WebSocketFrame closeFrame)
Called by the reading thread as its last step.
-
onWritingThreadFinished
void onWritingThreadFinished(WebSocketFrame closeFrame)
Called by the writing thread as its last step.
-
onThreadsFinished
private void onThreadsFinished()
Called when both the reading thread and the writing thread have finished. This method is called in the context of either the reading thread or the writing thread.
-
finish
void finish()
-
finishAsynchronously
private void finishAsynchronously()
Callfinish()from within a separate thread.
-
findAgreedPerMessageCompressionExtension
private PerMessageCompressionExtension findAgreedPerMessageCompressionExtension()
Find a per-message compression extension from among the agreed extensions.
-
getPerMessageCompressionExtension
PerMessageCompressionExtension getPerMessageCompressionExtension()
Get the PerMessageCompressionExtension in the agreed extensions. This method returns null if a per-message compression extension is not found in the agreed extensions.
-
-