使用HttpServlet的WebSocket代理

时间:2018-09-27 14:00:32

标签: java servlets websocket

我有一个问题。 也许有人可以向我解释,或者也许有人已经做到了-在我的项目中,我使用了基于Smiley's Http Proxy的http代理,几乎没有任何重构-对于HTTP和HTTPS来说,它工作得很好。但是现在,我必须代理Websocket应用程序。 因此,我找到了另一个库-Nv-WebSocket-Client。 当用户打开浏览器时,假设在http://somehost:8082/examples/websocket/chat.xhtml(我的应用代理到http://someanotherhost:8080/examples/websocket/chat.xhtml)上,这可以正常工作。然后-此页面上的javascript代码正在创建Websocket并重新设置ws:// somehost:8082 / examples / websocket / chat-我的应用程序代理了ws:// someanotherhost:8080 / examples / websocket / chat,并且它也可以正常工作, cuz握手已成功完成,并且响应已通过101交换协议返回到浏览器。但是后来我从weboscket真实服务器终结点收到了文本框架,我不知道如何将这个框架带给用户。也许有人知道一些可以为Websocket代理的库? 这是方法的一些代码:

private HttpResponse invokeWebSocketReq(HttpServletRequest servletRequest, HttpRequest proxyRequest){
    final HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,1), 101, "Switching protocol");
    try {


            WebSocketFactory factory = new WebSocketFactory();

            factory.setConnectionTimeout(5000);
            WebSocket webSocket = factory.createSocket(proxyRequest.getRequestLine().getUri());
            Header header = proxyRequest.getFirstHeader("Sec-WebSocket-Extensions");
            webSocket.addExtension(WebSocketExtension.parse(header.getValue()));
            webSocket.addHeader("Sec-WebSocket-Key", proxyRequest.getFirstHeader("Sec-WebSocket-Key").getValue());
            webSocket.setMissingCloseFrameAllowed(true);
            webSocket.addListener(new WebSocketAdapter() {
                ServerTest st;

                @Override
                public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
                    System.out.println("Successfully connected to websocket");
                    System.out.println("Is websocket open? - " + webSocket.isOpen());

                }

                @Override
                public void onConnectError(WebSocket websocket, WebSocketException exception) throws Exception {
                    super.onConnectError(websocket, exception);
                }

                @Override
                public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
                    System.out.println("Disconnected from websocket");
                    System.out.println("Server Close code: " + serverCloseFrame.getCloseCode());
                    System.out.println("Server Close reason: " + serverCloseFrame.getCloseReason());
                    System.out.println("Client Close code: " + clientCloseFrame.getCloseCode());
                    System.out.println("Client Close reason: " + clientCloseFrame.getCloseReason());
                }

                @Override
                public void onTextFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
                    System.out.println("OnTextFrame: " + frame.getPayloadText());

                }

                @Override
                public void onCloseFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
                    System.out.println("OnClose Frame");
                }

                @Override
                public void onTextMessage(WebSocket websocket, String text) throws Exception {
                    System.out.println("On Text Message: " + text);
                    System.out.println("Local socket address: " + websocket.getSocket().getLocalSocketAddress().toString());
                    System.out.println("Remote socket address" + websocket.getSocket().getRemoteSocketAddress().toString());
                    super.onTextMessage(websocket, text);
                }

                @Override
                public void onError(WebSocket websocket, WebSocketException cause) throws Exception {
                    System.out.println("Error: " + cause.getMessage());
                }

                @Override
                public void onSendError(WebSocket websocket, WebSocketException cause, WebSocketFrame frame) throws Exception {
                    System.out.println("On send error");
                }

                @Override
                public void onUnexpectedError(WebSocket websocket, WebSocketException cause) throws Exception {
                    System.out.println("On unexpected error");
                }

                @Override
                public void onSendingHandshake(WebSocket websocket, String requestLine, List<String[]> headers) throws Exception {
                    System.out.println("Will send handshake");
                    System.out.println("Request line: " + requestLine);
                    System.out.println("All headers: " + headers.toString());

                }

                @Override
                public void onStateChanged(WebSocket websocket, WebSocketState newState) throws Exception {
                    super.onStateChanged(websocket, newState);
                }

            });

            webSocket.connect();
            System.out.println("Is websocket open? - " + webSocket.isOpen());
            for (Map.Entry<String, List<String>> entry : webSocket.getServerHeaders().entrySet()) {
                httpResponse.setHeader(entry.getKey(), entry.getValue().get(0));
            }




    } catch (InterruptedException | ExecutionException | /*DeploymentException |*/ IOException | WebSocketException e) {
        e.printStackTrace();
        httpResponse.setStatusCode(500);
        httpResponse.setReasonPhrase(e.getMessage());
    }finally {
        System.out.println("Woopes");
    }
    return httpResponse;
}

我在tomcat websocket示例聊天中进行测试。另外,当用户尝试在聊天中输入内容时-我在浏览器控制台中收到此消息: “与'ws:// somehost:8082 / examples / websocket / chat'的WebSocket连接失败:服务器不得屏蔽它发送给客户端的任何帧。”

0 个答案:

没有答案