Skip to content

Using the WebSocket through a http proxy

Marcel Prestel edited this page Dec 24, 2017 · 2 revisions

Introduction

You can use a websocket through a http proxy.

Example

The following example was provided by shuckc

 public static void main( String[] args ) throws Exception {
        URI serverUri = new URI( "wss://ourapp.herokuapp.com:443/ws1" );
        WebSocketChatClient chatclient = new WebSocketChatClient( serverUri );

        Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress( "proxy.corporate.com", 2128) );

        Socket proxySocket = new Socket(proxy);
        String host = serverUri.getHost();
        int port = serverUri.getPort();
        proxySocket.connect(new InetSocketAddress(host, port));

        SSLContext sslContext = null;
        sslContext = SSLContext.getInstance( "TLS" );
        sslContext.init( null, null, null );

        SSLSocketFactory factory = sslContext.getSocketFactory();
        chatclient.setSocket( factory.createSocket(proxySocket, host, port, true) );
        chatclient.connectBlocking();

        BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
        while ( true ) {
            String line = reader.readLine();
            if( line.equals( "close" ) ) {
                chatclient.close();
            } else {
                chatclient.send("{\"msg\":\"" + line + "\"}");
            }
        }
    }