Tabnine Logo
WebSocket
Code IndexAdd Tabnine to your IDE (free)

How to use
WebSocket
in
com.neovisionaries.ws.client

Best Java code snippets using com.neovisionaries.ws.client.WebSocket (Showing top 20 results out of 315)

origin: TakahikoKawasaki/nv-websocket-client

  @Override
  public WebSocket call() throws WebSocketException
  {
    return mWebSocket.connect();
  }
}
origin: DV8FromTheWorld/JDA

protected void send(String message)
{
  LOG.trace("<- {}", message);
  socket.sendText(message);
}
origin: TakahikoKawasaki/nv-websocket-client

/**
 * Disconnect the WebSocket.
 *
 * <p>
 * This method is an alias of {@link #disconnect(int, String)
 * disconnect}{@code (}{@link WebSocketCloseCode#NORMAL}{@code , null)}.
 * </p>
 *
 * @return
 *         {@code this} object.
 */
public WebSocket disconnect()
{
  return disconnect(WebSocketCloseCode.NORMAL, null);
}
origin: TakahikoKawasaki/nv-websocket-client

private void doTask()
{
  synchronized (this)
  {
    if (mInterval == 0 || mWebSocket.isOpen() == false)
    {
      mScheduled = false;
      // Not schedule a new task.
      return;
    }
    // Create a frame and send it to the server.
    mWebSocket.sendFrame(createFrame());
    // Schedule a new task.
    mScheduled = schedule(mTimer, new Task(), mInterval);
  }
}
origin: DV8FromTheWorld/JDA

protected synchronized void connect()
{
  if (api.getStatus() != JDA.Status.ATTEMPTING_TO_RECONNECT)
    api.setStatus(JDA.Status.CONNECTING_TO_WEBSOCKET);
  if (shutdown)
    throw new RejectedExecutionException("JDA is shutdown!");
  initiating = true;
  String url = api.getGatewayUrl() + "?encoding=json&v=" + DISCORD_GATEWAY_VERSION;
  if (compression)
  {
    url += "&compress=zlib-stream";
    decompressBuffer = newDecompressBuffer();
  }
  try
  {
    socket = api.getWebSocketFactory()
        .createSocket(url)
        .addHeader("Accept-Encoding", "gzip")
        .addListener(this);
    socket.connect();
  }
  catch (IOException | WebSocketException e)
  {
    api.resetGatewayUrl();
    //Completely fail here. We couldn't make the connection.
    throw new IllegalStateException(e);
  }
}
origin: blockchain/Android-Merchant-App

    .addHeader("Origin", "https://blockchain.info").recreate()
    .addListener(new WebSocketAdapter() {
mConnection.connect();
origin: io.github.sac/SocketclusterClientJava

  e.printStackTrace();
ws.addExtension("permessage-deflate; client_max_window_bits");
for (Map.Entry<String, String> entry : headers.entrySet()) {
  ws.addHeader(entry.getKey(), entry.getValue());
ws.addListener(adapter);
  ws.connect();
} catch (OpeningHandshakeException e) {
origin: FlareBot/FlareBot

@Override
public WebSocket createSocket(URI uri) throws IOException {
  WebSocket socket = super.createSocket(uri);
  socket.addListener(this.listener);
  return socket;
}
origin: io.github.sac/SocketclusterClientJava

public void connectAsync() {
  try {
    ws = factory.createSocket(URL);
  } catch (IOException e) {
    e.printStackTrace();
  }
  ws.addExtension("permessage-deflate; client_max_window_bits");
  for (Map.Entry<String, String> entry : headers.entrySet()) {
    ws.addHeader(entry.getKey(), entry.getValue());
  }
  ws.addListener(adapter);
  ws.connectAsynchronously();
}
origin: stackoverflow.com

  wsf.setSSLContext(context);
  ws = wsf.createSocket("wss://" + ADDRESS);
  ws.addListener(new WSListener());
  ws.addExtension(WebSocketExtension.parse(WebSocketExtension.PERMESSAGE_DEFLATE));
  ws.connect();
} catch (Exception e) {
  e.printStackTrace();
origin: net.dv8tion/JDA

.addListener(this)
.connect();
origin: DV8FromTheWorld/JDA

protected void startConnection()
{
  if (!reconnecting && socket != null)
    throw new IllegalStateException("Somehow, someway, this AudioWebSocket has already attempted to start a connection!");
  try
  {
    socket = getJDA().getWebSocketFactory()
             .createSocket(wssEndpoint)
             .addListener(this);
    changeStatus(ConnectionStatus.CONNECTING_AWAITING_WEBSOCKET_CONNECT);
    socket.connectAsynchronously();
  }
  catch (IOException e)
  {
    LOG.warn("Encountered IOException while attempting to connect: {}\nClosing connection and attempting to reconnect.", e.getMessage());
    this.close(ConnectionStatus.ERROR_WEBSOCKET_UNABLE_TO_CONNECT);
  }
}
origin: twitch4j/twitch4j

this.webSocket.clearListeners();
this.webSocket.addListener(new WebSocketAdapter() {
origin: delight-im/Android-DDP

/**
 * Opens a connection to the server over websocket
 *
 * @param isReconnect whether this is a re-connect attempt or not
 */
private void openConnection(final boolean isReconnect) {
  if (isReconnect) {
    if (mConnected) {
      initConnection(mSessionID);
      return;
    }
  }
  // create a new WebSocket connection for the data transfer
  try {
    mWebSocket = new WebSocketFactory().setConnectionTimeout(30000).createSocket(mServerUri);
  }
  catch (final IOException e) {
    mCallbackProxy.onException(e);
  }
  mWebSocket.setMissingCloseFrameAllowed(true);
  mWebSocket.setPingInterval(25 * 1000);
  mWebSocket.addListener(mWebSocketListener);
  mWebSocket.connectAsynchronously();
}
origin: Javacord/Javacord

  websocket.removeListeners(identifyFrameListeners);
  identifyFrameListeners.clear();
websocket.addListener(identifyFrameListener);
logger.debug("Sending identify packet");
websocket.sendFrame(identifyFrame);
origin: blockchain/Android-Merchant-App

  private void send(String message) {
    //Make sure each message is only sent once per socket lifetime
    if(!sentMessageSet.contains(message)) {
      try {
        if (mConnection != null && mConnection.isOpen()) {
          mConnection.sendText(message);
          sentMessageSet.add(message);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
//            Log.d("WebSocketHandler", "Message sent already: "+message);
    }
  }

origin: twitch4j/twitch4j

/**
 * Disconnecting from WebSocket
 */
@Synchronized
public void disconnect() {
  if (connectionState.equals(TMIConnectionState.CONNECTED)) {
    connectionState = TMIConnectionState.DISCONNECTING;
  }
  connectionState = TMIConnectionState.DISCONNECTED;
  // CleanUp
  this.webSocket.clearListeners();
  this.webSocket.disconnect();
  this.webSocket = null;
}
origin: blockchain/Android-Merchant-App

public void stop() {
  stopPingTimer();
  if(mConnection != null && mConnection.isOpen()) {
    mConnection.disconnect();
  }
}
origin: TakahikoKawasaki/nv-websocket-client

if (mWebSocket.isOpen() == false)
origin: DV8FromTheWorld/JDA

public void close()
{
  if (socket != null)
    socket.sendClose(1000);
}
com.neovisionaries.ws.clientWebSocket

Javadoc

WebSocket.

Create WebSocketFactory

WebSocketFactory is a factory class that creates WebSocket instances. The first step is to create a WebSocketFactory instance.

 // Create a WebSocketFactory instance. 
WebSocketFactory factory = new  
WebSocketFactory#WebSocketFactory();

By default, WebSocketFactory uses javax.net.SocketFactory .javax.net.SocketFactory#getDefault() for non-secure WebSocket connections ( ws:) and javax.net.ssl.SSLSocketFactory.javax.net.ssl.SSLSocketFactory#getDefault() for secure WebSocket connections ( wss:). You can change this default behavior by using WebSocketFactory.WebSocketFactory#setSocketFactory(javax.net.SocketFactory) method, WebSocketFactory.WebSocketFactory#setSSLSocketFactory(javax.net.ssl.SSLSocketFactory) method and WebSocketFactory.WebSocketFactory#setSSLContext(javax.net.ssl.SSLContext) 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.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. 
WebSocketFactory#setSSLContext(javax.net.ssl.SSLContext)(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. 
WebSocketFactory#setVerifyHostname(boolean)(false);

NaiveSSLContext used in the above example is a factory class to create an javax.net.ssl.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.

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 WebSocketFactory instance before creating a WebSocketinstance. Proxy settings are represented by ProxySettingsclass. A WebSocketFactory instance has an associated ProxySettings instance and it can be obtained by calling WebSocketFactory.WebSocketFactory#getProxySettings() method.

 // Get the associated ProxySettings instance. 
ProxySettings settings = factory. 
WebSocketFactory#getProxySettings();

ProxySettings class has methods to set information about a proxy server such as ProxySettings#setHost(String)method and ProxySettings#setPort(int) method. The following is an example to set a secure (https) proxy server.

 // Set a proxy server. 
settings. 
ProxySettings#setServer(String)("https://proxy.example.com");

If credentials are required for authentication at a proxy server, ProxySettings#setId(String) method and ProxySettings#setPassword(String) method, or ProxySettings#setCredentials(String,String)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. 
ProxySettings#setCredentials(String,String)(id, password); 

Create WebSocket

WebSocket class represents a WebSocket. 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 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#WebSocketFactory(). 
WebSocketFactory#createSocket(String)("ws://localhost/endpoint");

There are two ways to set a timeout value for socket connection. The first way is to call WebSocketFactory#setConnectionTimeout(int) method of WebSocketFactory.

 // Create a WebSocket factory and set 5000 milliseconds as a timeout 
// value for socket connection. 
WebSocketFactory factory = new WebSocketFactory(). 
WebSocketFactory#setConnectionTimeout(int)(5000); 
// Create a WebSocket. The timeout value set above is used. 
WebSocket ws = factory. 
WebSocketFactory#createSocket(String)("ws://localhost/endpoint");

The other way is to give a timeout value to a createSocket method.

 // 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. 
WebSocketFactory#createSocket(String,int)("ws://localhost/endpoint", 5000);

The timeout value is passed to Socket#connect(java.net.SocketAddress,int) (java.net.SocketAddress , int)method of java.net.Socket.

Register Listener

After creating a WebSocket instance, you should call #addListener(WebSocketListener) method to register a WebSocketListener that receives WebSocket events. WebSocketAdapter is an empty implementation of WebSocketListener interface.

 // Register a listener to receive WebSocket events. 
ws. 
#addListener(WebSocketListener)(new  
WebSocketAdapter#WebSocketAdapter() { 
 
 @Override 
public void  
WebSocketListener#onTextMessage(WebSocket,String)(WebSocket websocket, String message) throws Exception { 
// Received a text message. 
...... 
} 
});

The table below is the list of callback methods defined in WebSocketListenerinterface.

WebSocketListener methods
Method Description
WebSocketListener#handleCallbackError(WebSocket,Throwable) Called when an onXxx() method threw a Throwable.
WebSocketListener#onBinaryFrame(WebSocket,WebSocketFrame) Called when a binary frame was received.
WebSocketListener#onBinaryMessage(WebSocket,byte[]) Called when a binary message was received.
WebSocketListener#onCloseFrame(WebSocket,WebSocketFrame) Called when a close frame was received.
WebSocketListener#onConnected(WebSocket,Map) Called after the opening handshake succeeded.
WebSocketListener#onConnectError(WebSocket,WebSocketException) Called when #connectAsynchronously() failed.
WebSocketListener#onContinuationFrame(WebSocket,WebSocketFrame) Called when a continuation frame was received.
WebSocketListener#onDisconnected(WebSocket,WebSocketFrame,WebSocketFrame,boolean) Called after a WebSocket connection was closed.
WebSocketListener#onError(WebSocket,WebSocketException) Called when an error occurred.
WebSocketListener#onFrame(WebSocket,WebSocketFrame) Called when a frame was received.
WebSocketListener#onFrameError(WebSocket,WebSocketException,WebSocketFrame) Called when a frame failed to be read.
WebSocketListener#onFrameSent(WebSocket,WebSocketFrame) Called when a frame was sent.
WebSocketListener#onFrameUnsent(WebSocket,WebSocketFrame) Called when a frame was not sent.
WebSocketListener#onMessageDecompressionError(WebSocket,WebSocketException,byte[]) Called when a message failed to be decompressed.
WebSocketListener#onMessageError(WebSocket,WebSocketException,List) Called when a message failed to be constructed.
WebSocketListener#onPingFrame(WebSocket,WebSocketFrame) Called when a ping frame was received.
WebSocketListener#onPongFrame(WebSocket,WebSocketFrame) Called when a pong frame was received.
WebSocketListener#onSendError(WebSocket,WebSocketException,WebSocketFrame) Called when an error occurred on sending a frame.
WebSocketListener#onSendingFrame(WebSocket,WebSocketFrame) Called before a frame is sent.
WebSocketListener#onSendingHandshake(WebSocket,String,List) Called before an opening handshake is sent.
WebSocketListener#onStateChanged(WebSocket,WebSocketState) Called when the state of WebSocket changed.
WebSocketListener#onTextFrame(WebSocket,WebSocketFrame) Called when a text frame was received.
WebSocketListener#onTextMessage(WebSocket,String) Called when a text message was received.
WebSocketListener#onTextMessageError(WebSocket,WebSocketException,byte[]) Called when a text message failed to be constructed.
WebSocketListener#onThreadCreated(WebSocket,ThreadType,Thread) Called after a thread was created.
WebSocketListener#onThreadStarted(WebSocket,ThreadType,Thread) Called at the beginning of a thread's run() method.
WebSocketListener#onThreadStopping(WebSocket,ThreadType,Thread) Called at the end of a thread's run() method.
WebSocketListener#onUnexpectedError(WebSocket,WebSocketException) Called when an uncaught throwable was detected.

Configure WebSocket

Before starting a WebSocket opening handshake with the server, you can configure the WebSocket instance by using the following methods.

Methods for Configuration
METHOD DESCRIPTION
#addProtocol(String) Adds an element to Sec-WebSocket-Protocol
#addExtension(WebSocketExtension) Adds an element to Sec-WebSocket-Extensions
#addHeader(String,String) Adds an arbitrary HTTP header.
#setUserInfo(String,String) Adds Authorization header for Basic Authentication.
#getSocket() Gets the underlying Socket instance to configure it.
#setExtended(boolean) Disables validity checks on RSV1/RSV2/RSV3 and opcode.
#setFrameQueueSize(int) Set the size of the frame queue for congestion control.
#setMaxPayloadSize(int) Set the maximum payload size.
#setMissingCloseFrameAllowed(boolean) Set 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, a WebSocketException would be thrown. Instead, when the handshake succeeds, the connect() 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 ( 
OpeningHandshakeException e) 
{ 
// A violation against the WebSocket protocol was detected 
// during the opening handshake. 
} 
catch ( 
HostnameUnverifiedException e) 
{ 
// The certificate of the peer does not match the expected hostname. 
} 
catch ( 
WebSocketException e) 
{ 
// Failed to establish a WebSocket connection. 
}

In some cases, connect() method throws OpeningHandshakeExceptionwhich is a subclass of WebSocketException (since version 1.19). OpeningHandshakeException provides additional methods such as OpeningHandshakeException#getStatusLine(), OpeningHandshakeException#getHeaders() and OpeningHandshakeException#getBody() to access the response from a server. The following snippet is an example to print information that the exception holds.

 catch ( 
OpeningHandshakeException e) 
{ 
// Status line. 
StatusLine sl = e. 
OpeningHandshakeException#getStatusLine(); 
System.out.println("=== Status Line ==="); 
System.out.format("HTTP Version  = %s\n", sl. 
StatusLine#getHttpVersion()); 
System.out.format("Status Code   = %d\n", sl. 
StatusLine#getStatusCode()); 
System.out.format("Reason Phrase = %s\n", sl. 
StatusLine#getReasonPhrase()); 
// HTTP headers. 
Map<String, List<String>> headers = e. 
OpeningHandshakeException#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 throws HostnameUnverifiedExceptionwhich is a subclass of WebSocketException (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 use #connectAsynchronously() method. The implementation of the method creates a thread and calls connect() method in the thread. When the connect() call failed, WebSocketListener#onConnectError(WebSocket,WebSocketException) 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 WebSocket#connect(java.util.concurrent.ExecutorService) (described below) will trigger the callback method.

 // Connect to the server 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. 
ExecutorService es =  
java.util.concurrent.Executors. 
java.util.concurrent.Executors#newSingleThreadExecutor(); 
// Connect to the server asynchronously. 
Future  future = ws. 
#connect(ExecutorService)(es); 
try 
{ 
// Wait for the opening handshake to complete. 
future.get(); 
} 
catch ( 
java.util.concurrent.ExecutionException e) 
{ 
if (e.getCause() instanceof  
WebSocketException) 
{ 
...... 
} 
}

The implementation of connect(ExecutorService) method creates a java.util.concurrent.Callable instance by calling #connectable() method and passes the instance to ExecutorService#submit(Callable)method of the given ExecutorService. What the implementation of Callable#call() method of the Callableinstance does is just to call the synchronous connect().

Send Frames

WebSocket 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(String)("Hello."); 
// Send a binary frame. 
byte[] binary = ......; 
ws. 
#sendBinary(byte[])(binary); 
// Send a ping frame. 
ws. 
#sendPing(String)("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 
. 
WebSocketFrame#createTextFrame(String)("How ") 
. 
WebSocketFrame#setFin(boolean)(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 
. 
WebSocketFrame#createContinuationFrame(String)("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 
. 
WebSocketFrame#createContinuationFrame(String)("you?") 
. 
WebSocketFrame#setFin(boolean)(true); 
// Send a text message which consists of 3 frames. 
ws. 
#sendFrame(WebSocketFrame)(firstFrame) 
. 
#sendFrame(WebSocketFrame)(secondFrame) 
. 
#sendFrame(WebSocketFrame)(lastFrame);

Alternatively, the same as above can be done like this.

 // Send a text message which consists of 3 frames. 
ws. 
#sendText(String,boolean)("How ", false) 
. 
#sendContinuation(String)("are ") 
. 
#sendContinuation(String,boolean)("you?", true);

Send Ping/Pong Frames Periodically

You can send ping frames periodically by calling #setPingInterval(long) 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(long)(60 * 1000); 
// Stop the periodical sending. 
ws. 
#setPingInterval(long)(0);

Likewise, you can send pong frames periodically by calling #setPongInterval(long) method. "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) and #setPongPayloadGenerator(PayloadGenerator) methods. Both methods take an instance of PayloadGenerator interface. The following is an example to use the string representation of the current date as payload of ping frames.

 ws. 
#setPingPayloadGenerator(PayloadGenerator)(new  
PayloadGenerator () { 
 
 @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 PayloadGenerator#generate() method must not exceed 125.

You can change the names of the java.util.Timers that send ping/pong frames periodically by using #setPingSenderName(String) and #setPongSenderName(String) methods.

 // Change the Timers' names. 
ws. 
#setPingSenderName(String)("PING_SENDER"); 
ws. 
#setPongSenderName(String)("PONG_SENDER"); 

Auto Flush

By default, a frame is automatically flushed to the server immediately after #sendFrame(WebSocketFrame) method is executed. This automatic flush can be disabled by calling #setAutoFlush(boolean)(false).

 // Disable auto-flush. 
ws. 
#setAutoFlush(boolean)(false);

To flush frames manually, call #flush() method. Note that this method works asynchronously.

 // Flush frames to the server manually. 
ws. 
#flush();

Congestion Control

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(int)(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.

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(int)(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 #addExtension(String) method with "permessage-deflate".

 // Enable "permessage-deflate" extension (RFC 7692). 
ws. 
#addExtension(String)( 
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 WebSocketListener#onError(WebSocket,WebSocketException) method nor WebSocketListener#onFrameError(WebSocket,WebSocketException,WebSocketFrame) method of WebSocketListener. If you want to make a WebSocket instance report an error in the case, pass false to #setMissingCloseFrameAllowed(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(boolean)(false);

Direct Text Message

When a text message was received, WebSocketListener#onTextMessage(WebSocket,String) is called. The implementation internally converts the byte array of the text message into a String object before calling the listener method. If you want to receive the byte array directly without the string conversion, call #setDirectTextMessage(boolean) with true, and WebSocketListener#onTextMessage(WebSocket,byte[])will be called instead.

 // Receive text messages without string conversion. 
ws. 
#setDirectTextMessage(boolean)(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 as #disconnect(int,String). disconnect()method itself is an alias of disconnect(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 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) method.

Note that you should not trigger reconnection in WebSocketListener#onError(WebSocket,WebSocketException) method because onError() may be called multiple times due to one error. Instead, WebSocketListener#onDisconnected(WebSocket,WebSocketFrame,WebSocketFrame,boolean) 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 in WebSocketListener callback 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

WebSocketListener has some onXxxError() methods such as WebSocketListener#onFrameError(WebSocket,WebSocketException,WebSocketFrame) and WebSocketListener#onSendError(WebSocket,WebSocketException,WebSocketFrame). Among such methods, WebSocketListener#onError(WebSocket,WebSocketException) 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 WebSocketListener#onUnexpectedError(WebSocket,WebSocketException) 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. 
WebSocketException cause = new WebSocketException( 
WebSocketError. 
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 for one error cause, so don't try to trigger reconnection in onError(). Instead, WebSocketListener#onDisconnected(WebSocket,WebSocketFrame,WebSocketFrame,boolean) 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 WebSocketException#getError() method which returns a WebSocketError enum entry. Entries in WebSocketErrorenum 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 WebSocketListener#handleCallbackError(WebSocket,Throwable) of WebSocketListener.

  
 @Override 
public void  
WebSocketListener#handleCallbackError(WebSocket,Throwable)(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
ThreadType#READING_THREAD A thread which reads WebSocket frames from the server.
ThreadType#WRITING_THREAD A thread which sends WebSocket frames to the server.
ThreadType#CONNECT_THREAD A thread which calls WebSocket#connect() asynchronously.
ThreadType#FINISH_THREAD A thread which does finalization of a WebSocket instance.

The following callback methods of WebSocketListener are called according to the life cycle of the threads.

Thread Callbacks
METHOD DESCRIPTION
WebSocketListener#onThreadCreated(WebSocket,ThreadType,Thread) Called after a thread was created.
WebSocketListener#onThreadStarted(WebSocket,ThreadType,Thread) Called at the beginning of the thread's run() method.
WebSocketListener#onThreadStopping(WebSocket,ThreadType,Thread) Called at the end of the thread's run() method.

For example, if you want to change the name of the reading thread, implement WebSocketListener#onThreadCreated(WebSocket,ThreadType,Thread) method like below.

  
 @Override 
public void  
WebSocketListener#onThreadCreated(WebSocket,ThreadType,Thread)(WebSocket websocket,  
ThreadType type, Thread thread) 
{ 
if (type == ThreadType.READING_THREAD) 
{ 
thread.setName("READING_THREAD"); 
} 
}

Most used methods

  • addListener
    Add a listener to receive events on this WebSocket.
  • connect
    Execute #connect() asynchronously using the given ExecutorService. This method is just an alias of t
  • sendText
    Send a text frame to the server. This method is an alias of #sendFrame(WebSocketFrame) (WebSocketFra
  • disconnect
    Disconnect the WebSocket. This method is an alias of #disconnect(int,String) (WebSocketCloseCode#NOR
  • addHeader
    Add a pair of extra HTTP header.
  • isOpen
    Check if the current state of this WebSocket is WebSocketState#OPEN.
  • connectAsynchronously
    Execute #connect() asynchronously by creating a new thread and calling connect() in the thread. If c
  • sendClose
    Send a close frame to the server. This method is an alias of #sendFrame(WebSocketFrame) (WebSocketFr
  • addExtension
    Add a value for Sec-WebSocket-Extension. The input string should comply with the format described in
  • clearListeners
    Remove all the listeners from this WebSocket.
  • recreate
    Create a new WebSocket instance that has the same settings as this instance. Note that, however, set
  • sendFrame
    Send a WebSocket frame to the server. This method just queues the given frame. Actual transmission i
  • recreate,
  • sendFrame,
  • setPingInterval,
  • <init>,
  • addListeners,
  • callOnConnectedIfNotYet,
  • changeStateOnConnect,
  • connectable,
  • findAgreedPerMessageCompressionExtension,
  • finish

Popular in Java

  • Making http post requests using okhttp
  • notifyDataSetChanged (ArrayAdapter)
  • onRequestPermissionsResult (Fragment)
  • getContentResolver (Context)
  • Pointer (com.sun.jna)
    An abstraction for a native pointer data type. A Pointer instance represents, on the Java side, a na
  • FileReader (java.io)
    A specialized Reader that reads from a file in the file system. All read requests made by calling me
  • Socket (java.net)
    Provides a client-side TCP socket.
  • MessageFormat (java.text)
    Produces concatenated messages in language-neutral way. New code should probably use java.util.Forma
  • BitSet (java.util)
    The BitSet class implements abit array [http://en.wikipedia.org/wiki/Bit_array]. Each element is eit
  • HttpServlet (javax.servlet.http)
    Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A sub
  • Best IntelliJ plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now