带有代理的Java websocket

时间:2015-04-03 10:32:48

标签: java sockets proxy websocket credentials

我几天都在尝试使用 Java 中的代理来使websocket工作。我尝试了不同的库,如

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

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

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

提前致谢

2 个答案:

答案 0 :(得分:5)

尝试 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

<强>的JavaDoc
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字节,不需要任何外部依赖。

答案 1 :(得分:0)

您可以尝试Tyrus(Java EE中WebSocket API的参考实现);客户端不需要运行任何Java EE服务器,如果您使用的是Java 7,则客户端可能是minimized to ~500kb

Client behing proxyDependencies应该提供足够的信息来尝试。