带有代理的Java websocket [英] Java websocket with proxy

查看:321
本文介绍了带有代理的Java websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying all day and night for couple of days trying to make websocket to work using proxy in Java. I tried different library like

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

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

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

But sadly these library doesn't support proxy with credentials. If you guys have known any other library that supports proxy then I would be appreciated.

提前致谢

推荐答案

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

Try nv-websocket-client library. It supports authentication at a proxy server. Note that, however, the current implementation supports Basic Authentication only.

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

The size of nv-websocket-client-1.3.jar is 62,854 bytes and it does not require any external dependencies.

这篇关于带有代理的Java websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆