Java websocket with proxy

2019-04-14 02:07发布

问题:

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.

Thanks in advance

回答1:

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();

Blog
WebSocket client library (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>

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



回答2:

You can try 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 should provide enough info to try.