public class WebSocket extends Object
WebSocketFactory is a factory class that creates
WebSocket instances. The first step is to create a
WebSocketFactory instance.
// Create a WebSocketFactory instance. WebSocketFactory factory = newWebSocketFactory();
By default, WebSocketFactory uses SocketFactory.getDefault() for
non-secure WebSocket connections (ws:) and SSLSocketFactory.getDefault() for secure WebSocket connections (wss:). You can change this default behavior by using
WebSocketFactory.setSocketFactory method, WebSocketFactory.setSSLSocketFactory method and WebSocketFactory.setSSLContext method. Note that you don't have to call a setSSL* method at all if you use the default SSL configuration.
Also note that calling setSSLSocketFactory method has no
meaning if you have called setSSLContext method. See the
description of WebSocketFactory.createSocket(URI) method for
details.
The following is an example to set a custom SSL context to a
WebSocketFactory instance. (Again, you don't have to call a
setSSL* 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);
NaiveSSLContext used in the above example is a factory class to
create an SSLContext which 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, try NaiveSSLContext.
If a WebSocket endpoint needs to be accessed via an HTTP proxy,
information about the proxy server has to be set to a WebSocketFactory instance before creating a WebSocket
instance. Proxy settings are represented by ProxySettings
class. A WebSocketFactory instance has an associated
ProxySettings instance and it can be obtained by calling
WebSocketFactory.getProxySettings() method.
// Get the associated ProxySettings instance.ProxySettingssettings = factory.getProxySettings();
ProxySettings class has methods to set information about
a proxy server such as setHost
method and setPort method. 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,
setId method and setPassword method, or
setCredentials
method 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);
WebSocket class represents a web socket. Its instances are
created by calling one of createSocket methods of a WebSocketFactory instance. Below is the simplest example to create
a WebSocket instance.
// Create a web socket. 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, or if HTTP proxy handshake or SSL handshake failed, // an IOException is thrown. WebSocket ws = newWebSocketFactory().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 of WebSocketFactory.
// Create a web socket factory and set 5000 milliseconds as a timeout // value for socket connection. WebSocketFactory factory = new WebSocketFactory().setConnectionTimeout(5000); // Create a web socket. 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 createSocket method.
// Create a web socket factory. The timeout value remains 0. WebSocketFactory factory = new WebSocketFactory(); // Create a web socket with a socket connection timeout value. WebSocket ws = factory.createWebSocket("ws://localhost/endpoint", 5000);
The timeout value is passed to connect(SocketAddress, int)
method of Socket.
After creating a WebSocket instance, you should call addListener(WebSocketListener) method to register a WebSocketListener that receives web socket events. WebSocketAdapter is an empty implementation of WebSocketListener interface.
// Register a listener to receive web socket events. ws.addListener(newWebSocketAdapter(){@Override public voidonTextMessage(WebSocket websocket, String message) throws Exception { // Received a text message. ...... } });
Before starting a WebSocket opening handshake with the server, you can configure the web socket instance 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.setExtendedDisables validity checks on RSV1/RSV2/RSV3 and opcode. setFrameQueueSizeSet the size of the frame queue for congestion control.
By calling connect() method, a WebSocket opening handshake
is performed synchronously. If an error occurred during the handshake,
a WebSocketException would be thrown. Instead, when the
handshake succeeds, the connect() implementation creates
threads and starts them to read and write web socket frames
asynchronously.
try
{
// Perform an opening handshake.
// This method blocks until the opening handshake is finished.
ws.connect();
}
catch (WebSocketException e)
{
// Failed.
}
The simplest way to call connect() method asynchronously is to
use connectAsynchronously() method. The implementation of the
method creates a thread and calls connect() method in the thread.
When the connect() call failed, onConnectError() of WebSocketListener would be called. Note that
onConnectError() is called only when connectAsynchronously()
was used and the connect() call executed in the background thread
failed. Neither direct synchronous connect() nor
connect(ExecutorService) (described below) will trigger the callback method.
// Perform an opening handshake asynchronously. ws.connectAsynchronously();
Another way to call connect() method asynchronously is to use
connect(ExecutorService) method. The method performs a WebSocket
opening handshake asynchronously using the given ExecutorService.
// Prepare an ExecutorService.ExecutorServicees =Executors.newSingleThreadExecutor(); // Perform an opening handshake 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
a Callable<WebSocket>
instance by calling connectable() method and passes the
instance to submit(Callable)
method of the given ExecutorService. What the implementation
of call() method of the Callable
instance does is just to call the synchronous connect().
Web socket frames can be sent by sendFrame(WebSocketFrame)
method. Other sendXxx methods such as sendText(String) are aliases of sendFrame method. All of
the sendXxx methods work asynchronously.
However, under some conditions, sendXxx methods
may block. See Congestion Control
for details.
Below
are some examples of sendXxx methods. Note that
in normal cases, you don't have to call sendClose() method
and sendPong() (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);
You can send ping frames periodically by calling setPingInterval method with an interval in milliseconds between ping frames.
This method can be called both before and after connect() 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 setPongInterval method. "A Pong frame MAY be sent
unsolicited." (RFC 6455, 5.5.3. Pong)
By default, a frame is automatically flushed to the server immediately after
sendFrame method is executed. This automatic
flush can be disabled by calling setAutoFlush(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();
sendXxx methods queue a WebSocketFrame instance to the
internal queue. By default, no upper limit is imposed on the queue size, so
sendXxx methods 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 want
sendXxx methods 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 a sendXxx method 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, sendXxx
methods 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() and sendPing()) do not block.
Before a web socket 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 web socket 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 as disconnect(int, String). disconnect()
method itself is an alias of disconnect(WebSocketCloseCode.NORMAL, null).
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 new WebSocket instance again by calling one of createSocket methods of a WebSocketFactory. You may find recreate()
method useful if you want to create a new WebSocket instance that has the
same settings as the original instance. Note that, however, settings you made on
the raw socket of the original WebSocket instance 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 existing WebSocket instance was created, use recreate(int timeout) method.
Note that you should not trigger reconnection in onError() method
because onError() may be called multiple times due to one error. Instead,
onDisconnected() is the right place to trigger reconnection.
WebSocketListener has some onXxxError() methods such as onFrameError() and onSendError(). Among such methods, onError() is a special
one. It is always called before any other onXxxError() is called. For
example, in the implementation of run() method of ReadingThread,
Throwable is caught and onError() and onUnexpectedError() 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
that onError() may be called multiple times due to one error, so don't
try to trigger reconnection in onError(). Instead, onDiconnected() is the right place to trigger reconnection.
All onXxxError() methods receive a WebSocketException instance
as the second argument (the first argument is a WebSocket instance). The
exception class provides getError() method
which returns a WebSocketError enum entry. Entries in WebSocketError
enum 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 of onXXX() callback methods
are passed to handleCallbackError() of WebSocketListener.
@Override public voidhandleCallbackError(WebSocket websocket, Throwable cause) throws Exception { // Throwables thrown by onXxx() callback methods come here. }
| Modifier and Type | Method and Description |
|---|---|
WebSocket |
addExtension(String extension)
Add a value for
Sec-WebSocket-Extension. |
WebSocket |
addExtension(WebSocketExtension extension)
Add a value for
Sec-WebSocket-Extension. |
WebSocket |
addHeader(String name,
String value)
Add a pair of extra HTTP header.
|
WebSocket |
addListener(WebSocketListener listener)
Add a listener to receive events on this web socket.
|
WebSocket |
addListeners(List<WebSocketListener> listeners)
Add listeners.
|
WebSocket |
addProtocol(String protocol)
Add a value for
Sec-WebSocket-Protocol. |
WebSocket |
clearExtensions()
Remove all extensions from
Sec-WebSocket-Extension. |
WebSocket |
clearHeaders()
Clear all extra HTTP headers.
|
WebSocket |
clearListeners()
Remove all the listeners from this web socket.
|
WebSocket |
clearProtocols()
Remove all protocols from
Sec-WebSocket-Protocol. |
WebSocket |
clearUserInfo()
Clear the credentials to connect to the web socket endpoint.
|
WebSocket |
connect()
Send an opening handshake to the server, receive the response and then
start threads to communicate with the server.
|
Future<WebSocket> |
connect(ExecutorService executorService)
Execute
connect() asynchronously using the given ExecutorService. |
Callable<WebSocket> |
connectable()
|
WebSocket |
connectAsynchronously()
Execute
connect() asynchronously by creating a new thread and
calling connect() in the thread. |
WebSocket |
disconnect()
Disconnect the web socket.
|
WebSocket |
disconnect(int closeCode)
Disconnect the web socket.
|
WebSocket |
disconnect(int closeCode,
String reason)
Disconnect the web socket.
|
WebSocket |
disconnect(String reason)
Disconnect the web socket.
|
protected void |
finalize() |
WebSocket |
flush()
Flush frames to the server.
|
List<WebSocketExtension> |
getAgreedExtensions()
Get the agreed extensions.
|
String |
getAgreedProtocol()
Get the agreed protocol.
|
int |
getFrameQueueSize()
Get the size of the frame queue.
|
long |
getPingInterval()
Get the interval of periodical
ping
frames.
|
long |
getPongInterval()
Get the interval of periodical
pong
frames.
|
Socket |
getSocket()
Get the raw socket which this web socket uses internally.
|
WebSocketState |
getState()
Get the current state of this web socket.
|
URI |
getURI()
Get the URI of the web socket endpoint.
|
boolean |
isAutoFlush()
Check if flush is performed automatically after
sendFrame(WebSocketFrame) is done. |
boolean |
isExtended()
Check if extended use of web socket frames are allowed.
|
boolean |
isOpen()
Check if the current state of this web socket is
OPEN. |
WebSocket |
recreate()
Create a new
WebSocket instance that has the same settings
as this instance. |
WebSocket |
recreate(int timeout)
Create a new
WebSocket instance that has the same settings
as this instance. |
WebSocket |
removeExtension(WebSocketExtension extension)
Remove an extension from
Sec-WebSocket-Extension. |
WebSocket |
removeExtensions(String name)
Remove extensions from
Sec-WebSocket-Extension by
an extension name. |
WebSocket |
removeHeaders(String name)
Remove pairs of extra HTTP headers.
|
WebSocket |
removeListener(WebSocketListener listener)
Remove a listener from this web socket.
|
WebSocket |
removeListeners(List<WebSocketListener> listeners)
Remove listeners.
|
WebSocket |
removeProtocol(String protocol)
Remove a protocol from
Sec-WebSocket-Protocol. |
WebSocket |
sendBinary(byte[] message)
Send a binary message to the server.
|
WebSocket |
sendBinary(byte[] payload,
boolean fin)
Send a binary frame to the server.
|
WebSocket |
sendClose()
Send a close frame to the server.
|
WebSocket |
sendClose(int closeCode)
Send a close frame to the server.
|
WebSocket |
sendClose(int closeCode,
String reason)
Send a close frame to the server.
|
WebSocket |
sendContinuation()
Send a continuation frame to the server.
|
WebSocket |
sendContinuation(boolean fin)
Send a continuation frame to the server.
|
WebSocket |
sendContinuation(byte[] payload)
Send a continuation frame to the server.
|
WebSocket |
sendContinuation(byte[] payload,
boolean fin)
Send a continuation frame to the server.
|
WebSocket |
sendContinuation(String payload)
Send a continuation frame to the server.
|
WebSocket |
sendContinuation(String payload,
boolean fin)
Send a continuation frame to the server.
|
WebSocket |
sendFrame(WebSocketFrame frame)
Send a web socket frame to the server.
|
WebSocket |
sendPing()
Send a ping frame to the server.
|
WebSocket |
sendPing(byte[] payload)
Send a ping frame to the server.
|
WebSocket |
sendPing(String payload)
Send a ping frame to the server.
|
WebSocket |
sendPong()
Send a pong frame to the server.
|
WebSocket |
sendPong(byte[] payload)
Send a pong frame to the server.
|
WebSocket |
sendPong(String payload)
Send a pong frame to the server.
|
WebSocket |
sendText(String message)
Send a text message to the server.
|
WebSocket |
sendText(String payload,
boolean fin)
Send a text frame to the server.
|
WebSocket |
setAutoFlush(boolean auto)
Enable or disable auto-flush of sent frames.
|
WebSocket |
setExtended(boolean extended)
Allow or disallow extended use of web socket frames.
|
WebSocket |
setFrameQueueSize(int size)
Set the size of the frame queue.
|
WebSocket |
setPingInterval(long interval)
Set the interval of periodical
ping
frames.
|
WebSocket |
setPongInterval(long interval)
Set the interval of periodical
pong
frames.
|
WebSocket |
setUserInfo(String userInfo)
Set the credentials to connect to the web socket endpoint.
|
WebSocket |
setUserInfo(String id,
String password)
Set the credentials to connect to the web socket endpoint.
|
public WebSocket recreate() throws IOException
WebSocket instance that has the same settings
as this instance. Note that, however, settings you made on the raw
socket are not copied.
The WebSocketFactory instance that you used to create this
WebSocket instance 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, use recreate(int) method instead.
WebSocket instance.IOException - WebSocketFactory.createSocket(URI) threw an exception.public WebSocket recreate(int timeout) throws IOException
WebSocket instance that has the same settings
as this instance. Note that, however, settings you made on the raw
socket are not copied.
The WebSocketFactory instance that you used to create this
WebSocket instance is used again.
timeout - The timeout value in milliseconds for socket timeout.
A timeout of zero is interpreted as an infinite timeout.WebSocket instance.IllegalArgumentException - The given timeout value is negative.IOException - WebSocketFactory.createSocket(URI) threw an exception.protected void finalize()
throws Throwable
public WebSocketState getState()
The initial state is CREATED.
When connect() is called, the state is changed to
CONNECTING, and then to
OPEN after a successful opening
handshake. The state is changed to CLOSING when a closing handshake
is started, and then to CLOSED
when the closing handshake finished.
See the description of WebSocketState for details.
WebSocketStatepublic boolean isOpen()
OPEN.true if the current state is OPEN.public WebSocket addProtocol(String protocol)
Sec-WebSocket-Protocol.protocol - A protocol name.this object.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.public WebSocket removeProtocol(String protocol)
Sec-WebSocket-Protocol.protocol - A protocol name. null is silently ignored.this object.public WebSocket clearProtocols()
Sec-WebSocket-Protocol.this object.public WebSocket addExtension(WebSocketExtension extension)
Sec-WebSocket-Extension.extension - An extension. null is silently ignored.this object.public WebSocket addExtension(String extension)
Sec-WebSocket-Extension. The input string
should comply with the format described in 9.1. Negotiating
Extensions in RFC 6455.extension - A string that represents a WebSocket extension. If it does
not comply with RFC 6455, no value is added to Sec-WebSocket-Extension.this object.public WebSocket removeExtension(WebSocketExtension extension)
Sec-WebSocket-Extension.extension - An extension to remove. null is silently ignored.this object.public WebSocket removeExtensions(String name)
Sec-WebSocket-Extension by
an extension name.name - An extension name. null is silently ignored.this object.public WebSocket clearExtensions()
Sec-WebSocket-Extension.this object.public WebSocket addHeader(String name, String value)
name - An HTTP header name. When null or an empty
string is given, no header is added.value - The value of the HTTP header.this object.public WebSocket removeHeaders(String name)
name - An HTTP header name. null is silently ignored.this object.public WebSocket clearHeaders()
this object.public WebSocket setUserInfo(String userInfo)
userInfo - The credentials for Basic Authentication. The format
should be id:password.this object.public WebSocket setUserInfo(String id, String password)
id - The ID.password - The password.this object.public WebSocket clearUserInfo()
this object.public boolean isExtended()
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,
onFrameError method of
listeners are called and the web socket is eventually closed.
true if extended use of web socket frames
are allowed.public WebSocket setExtended(boolean extended)
extended - true to allow extended use of web socket frames.this object.public boolean isAutoFlush()
sendFrame(WebSocketFrame) is done. The default value is
true.true if flush is performed automatically.public WebSocket setAutoFlush(boolean auto)
auto - true to enable auto-flush. false to
disable it.this object.public WebSocket flush()
this object.public int getFrameQueueSize()
public WebSocket setFrameQueueSize(int size) throws IllegalArgumentException
sendXxx methods queue a WebSocketFrame
instance 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
a sendXxx method is called, the method blocks
until the queue gets spaces.
Under some conditions, even if the queue is full, sendXxx
methods 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() and sendPing()) do not block.
size - The queue size. 0 means no limit. Negative numbers are not allowed.this object.IllegalArgumentException - size is negative.public long getPingInterval()
public WebSocket setPingInterval(long interval)
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.
interval - The interval in milliseconds. A negative value is
regarded as zero.this object.public long getPongInterval()
public WebSocket setPongInterval(long interval)
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.
interval - The interval in milliseconds. A negative value is
regarded as zero.this object.public WebSocket addListener(WebSocketListener listener)
listener - A listener to add.this object.public WebSocket addListeners(List<WebSocketListener> listeners)
listeners - Listeners to add. null is silently ignored.
null elements in the list are ignored, too.this object.public WebSocket removeListener(WebSocketListener listener)
listener - A listener to remove. null won't cause an error.this object.public WebSocket removeListeners(List<WebSocketListener> listeners)
listeners - Listeners to remove. null is silently ignored.
null elements in the list are ignored, too.this object.public WebSocket clearListeners()
this object.public Socket getSocket()
Socket instance.public URI getURI()
"ws" or "wss". The authority part is always empty.public WebSocket connect() throws WebSocketException
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.
WebSocket websocket = ......; websocket.getSocket().setSoTimeout(5000);
If the web socket endpoint requires Basic Authentication, you can set
credentials by setUserInfo(userInfo) or
setUserInfo(id, password) before
you call this method.
Note that if the URI passed to WebSocketFactory.createSocket method contains the user-info part, you don't have to
call setUserInfo method.
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 WebSocket
instance again by calling one of createSocket methods of a
WebSocketFactory. You may find recreate() method
useful if you want to create a new WebSocket instance that
has the same settings as this instance. (But settings you made on
the raw socket are not copied.)
this object.WebSocketException - CREATED
public Future<WebSocket> connect(ExecutorService executorService)
connect() asynchronously using the given ExecutorService. This method is just an alias of the following.
executorService.submit(connectable())
executorService - An ExecutorService to execute a task created by
connectable().ExecutorService.submit(Callable).NullPointerException - If the given ExecutorService is null.RejectedExecutionException - If the given ExecutorService rejected the task
created by connectable().connectAsynchronously()public Callable<WebSocket> connectable()
Callable<WebSocket> instance
whose call() method calls connect()
method of this WebSocket instance.Callable<WebSocket> instance
for asynchronous connect().connect(ExecutorService)public WebSocket connectAsynchronously()
connect() asynchronously by creating a new thread and
calling connect() in the thread. If connect() failed,
onConnectError() method of WebSocketListener is called.this object.public WebSocket disconnect()
This method is an alias of disconnect(WebSocketCloseCode.NORMAL, null).
this object.public WebSocket disconnect(int closeCode)
This method is an alias of disconnect(closeCode, null).
closeCode - The close code embedded in a close frame
which this WebSocket client will send to the server.this object.public WebSocket disconnect(String reason)
This method is an alias of disconnect(WebSocketCloseCode.NORMAL, reason).
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.this object.public WebSocket disconnect(int closeCode, String reason)
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.this object.WebSocketCloseCode,
RFC 6455, 5.5.1. Closepublic List<WebSocketExtension> getAgreedExtensions()
This method works correctly only after connect() succeeds
(= after the opening handshake succeeds).
public String getAgreedProtocol()
This method works correctly only after connect() succeeds
(= after the opening handshake succeeds).
public WebSocket sendFrame(WebSocketFrame frame)
This method just queues the given frame. Actual transmission is performed asynchronously.
When the current state of this web socket is not OPEN, this method does not accept
the frame.
Sending a close frame changes the state to CLOSING (if the current state is neither CLOSING nor CLOSED).
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.
frame - A web socket frame to be sent to the server.
If null is given, nothing is done.this object.public WebSocket sendContinuation()
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, use sendContinuation(boolean fin) with fin=true.
this object.public WebSocket sendContinuation(boolean fin)
This method is an alias of sendFrame(WebSocketFrame.createContinuationFrame().setFin(fin)).
fin - The FIN bit value.this object.public WebSocket sendContinuation(String payload)
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, use sendContinuation(String payload, boolean fin) with fin=true.
payload - The payload of a continuation frame.this object.public WebSocket sendContinuation(String payload, boolean fin)
This method is an alias of sendFrame(WebSocketFrame.createContinuationFrame(payload).setFin(fin)).
payload - The payload of a continuation frame.fin - The FIN bit value.this object.public WebSocket sendContinuation(byte[] payload)
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, use sendContinuation(byte[] payload, boolean fin) with fin=true.
payload - The payload of a continuation frame.this object.public WebSocket sendContinuation(byte[] payload, boolean fin)
This method is an alias of sendFrame(WebSocketFrame.createContinuationFrame(payload).setFin(fin)).
payload - The payload of a continuation frame.fin - The FIN bit value.this object.public WebSocket sendText(String message)
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) with fin=false.
message - A text message to be sent to the server.this object.public WebSocket sendText(String payload, boolean fin)
This method is an alias of sendFrame(WebSocketFrame.createTextFrame(payload).setFin(fin)).
payload - The payload of a text frame.fin - The FIN bit value.this object.public WebSocket sendBinary(byte[] message)
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) with fin=false.
message - A binary message to be sent to the server.this object.public WebSocket sendBinary(byte[] payload, boolean fin)
This method is an alias of sendFrame(WebSocketFrame.createBinaryFrame(payload).setFin(fin)).
payload - The payload of a binary frame.fin - The FIN bit value.this object.public WebSocket sendClose()
This method is an alias of sendFrame(WebSocketFrame.createCloseFrame()).
this object.public WebSocket sendClose(int closeCode)
This method is an alias of sendFrame(WebSocketFrame.createCloseFrame(closeCode)).
closeCode - The close code.this object.WebSocketCloseCodepublic WebSocket sendClose(int closeCode, String reason)
This method is an alias of sendFrame(WebSocketFrame.createCloseFrame(closeCode, reason)).
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).this object.WebSocketCloseCodepublic WebSocket sendPing()
This method is an alias of sendFrame(WebSocketFrame.createPingFrame()).
this object.public WebSocket sendPing(byte[] payload)
This method is an alias of sendFrame(WebSocketFrame.createPingFrame(payload)).
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).this object.public WebSocket sendPing(String payload)
This method is an alias of sendFrame(WebSocketFrame.createPingFrame(payload)).
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).this object.public WebSocket sendPong()
This method is an alias of sendFrame(WebSocketFrame.createPongFrame()).
this object.public WebSocket sendPong(byte[] payload)
This method is an alias of sendFrame(WebSocketFrame.createPongFrame(payload)).
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).this object.public WebSocket sendPong(String payload)
This method is an alias of sendFrame(WebSocketFrame.createPongFrame(payload)).
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).this object.Copyright © 2015. All rights reserved.