High-quality WebSocket client implementation in Java which
wss) through "Secure Proxy" (https),Apache License, Version 2.0
<dependency>
<groupId>com.neovisionaries</groupId>
<artifactId>nv-websocket-client</artifactId>
<version>2.14</version>
</dependency>
dependencies {
compile 'com.neovisionaries:nv-websocket-client:2.14'
}
Bundle-SymbolicName: com.neovisionaries.ws.client
Export-Package: com.neovisionaries.ws.client;version="2.14.0"
https://github.com/TakahikoKawasaki/nv-websocket-client.git
https://TakahikoKawasaki.github.io/nv-websocket-client/
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();
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);
// 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 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.
SNI (Server Name Indication) is supported since version 2.4. To set up server
names, call either setServerNames(String[]) method or setServerName(String)
method. If your system has SSLParameters.setServerNames(List<SNIServerName>)
method, the method is called via reflection. Note that SSLParameters.setServerNames
is a relatively new method and it is not available before Java 1.8 and Android
7.0 (API Level 24).
// Set a server name for SNI (Server Name Indication).
factory.setServerName("example.com");
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.
ProxySettings settings = 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);
SNI (Server Name Indication) is supported since version 2.4. To set up server
names, call either setServerNames(String[]) method or setServerName(String)
method. If your system has SSLParameters.setServerNames(List<SNIServerName>)
method, the method is called via reflection. Note that SSLParameters.setServerNames
is a relatively new method and it is not available before Java 1.8 and Android
7.0 (API Level 24).
// Set a server name for SNI (Server Name Indication).
settings.setServerName("example.com");
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().createSocket("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 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.createSocket("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.createSocket("ws://localhost/endpoint", 5000);
The timeout value is passed to connect(SocketAddress, int) method of
java.net.Socket.
After creating a WebSocket instance, you should call addListener 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(new WebSocketAdapter() {
@Override
public void onTextMessage(WebSocket websocket, String message) throws Exception {
// Received a text message.
......
}
});
The table below is the list of callback methods defined in WebSocketListener
interface.
| Method | Description |
|---|---|
handleCallbackError |
Called when an onXxx() method threw a Throwable. |
onBinaryFrame |
Called when a binary frame was received. |
onBinaryMessage |
Called when a binary message was received. |
onCloseFrame |
Called when a close frame was received. |
onConnected |
Called after the opening handshake succeeded. |
onConnectError |
Called when connectAsynchronously() failed. |
onContinuationFrame |
Called when a continuation frame was received. |
onDisconnected |
Called after a WebSocket connection was closed. |
onError |
Called when an error occurred. |
onFrame |
Called when a frame was received. |
onFrameError |
Called when a frame failed to be read. |
onFrameSent |
Called when a frame was sent. |
onFrameUnsent |
Called when a frame was not sent. |
onMessageDecompressionError |
Called when a message failed to be decompressed. |
onMessageError |
Called when a message failed to be constructed. |
onPingFrame |
Called when a ping frame was received. |
onPongFrame |
Called when a pong frame was received. |
onSendError |
Called when an error occurred on sending a frame. |
onSendingFrame |
Called before a frame is sent. |
onSendingHandshake |
Called before an opening handshake is sent. |
onStateChanged |
Called when the state of WebSocket changed. |
onTextFrame |
Called when a text frame was received. |
onTextMessage |
Called when a text message was received. |
onTextMessageError |
Called when a text message failed to be constructed. |
onThreadCreated |
Called after a thread was created. |
onThreadStarted |
Called at the beginning of a thread's run() method. |
onThreadStopping |
Called at the end of a thread's run() method. |
onUnexpectedError |
Called when an uncaught throwable was detected. |
Before starting a WebSocket opening handshake with the server, you can configure the WebSocket instance by using the following methods.
| METHOD | DESCRIPTION |
|---|---|
addProtocol |
Adds an element to Sec-WebSocket-Protocol. |
addExtension |
Adds an element to Sec-WebSocket-Extensions. |
addHeader |
Adds an arbitrary HTTP header. |
setUserInfo |
Adds Authorization header for Basic Authentication. |
getSocket |
Gets the underlying Socket instance to configure it. Note that this may return null since version 2.9. Consider using getConnectedSocket() as necessary. |
getConnectedSocket |
Establishes and gets the underlying Socket instance to configure it. Available since version 2.9. |
setExtended |
Disables validity checks on RSV1/RSV2/RSV3 and opcode. |
setFrameQueueSize |
Set the size of the frame queue for congestion control. |
setMaxPayloadSize |
Set the maximum payload size. |
setMissingCloseFrameAllowed |
Set to whether to allow the server to close the connection without sending a close frame. |
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, if
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 OpeningHandshakeException which
is a subclass of WebSocketException (since version 1.19).
OpeningHandshakeException provides additional methods such as
getStatusLine(), getHeaders() and getBody() to access the response
from a server. The following snippet is an example to print information
that the exception holds.
```java catch (OpeningHandshakeException e) { // Status line. StatusLine sl = e.getStatusLine(); System.out
$ claude mcp add nv-websocket-client \
-- python -m otcore.mcp_server <graph>