百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
N

nv-websocket-client

> 编程语言
开源

Java 中高质量的 WebSocket 客户端实现。

2.1K stars0 点赞2 次浏览
访问官网GitHub

工具介绍

Java 中高质量的 WebSocket 客户端实现。

nv-websocket-client

Overview

High-quality WebSocket client implementation in Java which

  • complies with RFC 6455 (The WebSocket Protocol),
  • works on Java SE 1.5+ and Android,
  • supports all the frame types (continuation, binary, text, close, ping and pong),
  • provides a method to send a fragmented frame in addition to methods for unfragmented frames,
  • provides a method to get the underlying raw socket of a WebSocket to configure it,
  • provides a method for Basic Authentication,
  • provides a factory class which utilizes javax.net.SocketFactory interface,
  • provides a rich listener interface to hook WebSocket events,
  • has fine-grained error codes for fine-grained controllability on errors,
  • allows to disable validity checks on RSV1/RSV2/RSV3 bits and opcode of frames,
  • supports HTTP proxy, especially "Secure WebSocket" (wss) through "Secure Proxy" (https),
  • and supports RFC 7692 (Compression Extensions for WebSocket), also known as permessage-deflate (not enabled by default).

License

Apache License, Version 2.0

Maven

xml
<dependency>
    <groupId>com.neovisionaries</groupId>
    <artifactId>nv-websocket-client</artifactId>
    <version>2.14</version>
</dependency>

Gradle

gradle
dependencies {
    compile 'com.neovisionaries:nv-websocket-client:2.14'
}

OSGi

Bundle-SymbolicName: com.neovisionaries.ws.client
Export-Package: com.neovisionaries.ws.client;version="2.14.0"

Source Code

https://github.com/TakahikoKawasaki/nv-websocket-client.git

JavaDoc

https://TakahikoKawasaki.github.io/nv-websocket-client/

Description

Create WebSocketFactory

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

java
// 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.)

…

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

java
// Set a server name for SNI (Server Name Indication).
factory.setServerName("example.com");

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 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.

java
// 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.

java
// 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.

java
// 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).

java
// Set a server name for SNI (Server Name Indication).
settings.setServerName("example.com");

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.

java
// 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.

java
// 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.

java
// 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.

Register Listener

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.

java
// 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.

Configure WebSocket

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.

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 dur

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Java

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言