Java 带代理的 websocket

Java websocket with proxy

几天来,我一直在日以继夜地尝试让 websocket 在 Java 中使用代理工作。我尝试了不同的库,比如

https://github.com/TooTallNate/Java-WebSocket

https://github.com/AsyncHttpClient/async-http-client

但遗憾的是,这些库不支持凭据代理。如果你们知道任何其他支持代理的库,那么我将不胜感激。

提前致谢

你可以试试Tyrus (reference implementation of WebSocket API in Java EE); client side does not require any Java EE server to be running and if you are using Java 7, the client could be minimized to ~500kb.

Client behing proxy and Dependencies 应该提供足够的信息来尝试。

尝试 nv-websocket-client 库。它支持在代理服务器上进行身份验证。但是请注意,当前实现仅支持基本身份验证。

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

// 2. Set up information about a proxy server.
//    Credentials can be set here.
ProxySettings settings = factory.getProxySettings();
settings.setServer("http://proxy.example.com");
settings.setCredentials("id", "password");

// 3. Connect to a WebSocket endpoint via the proxy.
WebSocket ws = factory.createSocket("ws://websocket.example.com");

// 4. Add a listener to receive WebSocket events.
ws.addListener(new WebSocketAdapter() {
    @Override
    public void onTextMessage(WebSocket ws, String message) {
        // Received a text message.
        ......
    }
});

// 5. Perform a WebSocket opening handshake.
ws.connect();

// 6. Send frames.

// 6-1. Text
ws.sendText("Hello.");

// 6-2. Binary
byte[] binary = ......;
ws.sendBinary(binary);

// 6-3. Ping
ws.sendPing("Are you there?");

// 6-4. Pong (unsolicited pong; RFC 6455, 5.5.3. Pong)
ws.sendPong("I'm OK.");

// 6-5. Fragmented Frames
ws.sendText("How ", false)
  .sendContinuation("are ")
  .sendContinuation("you?", true);

// 6-6. Periodical Ping
ws.setPingInterval(60 * 1000);

// 6-7. Periodical Pong (unsolicited pong; RFC 6455, 5.5.3. Pong)
ws.setPongInterval(60 * 1000);

// 6-8. Close (if you want to send one manually).
ws.sendClose(WebSocketCloseCode.NORMAL, "Bye.");

// 7. Disconnect
ws.disconnect();

博客
WebSocket 客户端库(Java SE 1.5+,Android)
http://darutk-oboegaki.blogspot.jp/2015/05/websocket-client-library-java-se-15.html

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

Java文档
http://takahikokawasaki.github.io/nv-websocket-client/

Maven

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

nv-websocket-client-1.3.jar大小为62,854字节,不需要任何外部依赖。