2017-11-21 3 views
0

netty 프레임 작업 버전 4.1.6을 사용하여 websocket 서버를 개발 중입니다. 내가 netty example site 에서 샘플 코드를 사용하고 이 내 서버의 소스 코드 :자바 스크립트 클라이언트와 netty 서버 간의 안전한 웹 소켓 연결

public class WebSocketServer 
{ 
    static final int PORT = 4466; 
    public static void main(String[] args) 
    { 
     final SslContext sslCtx; 
     EventLoopGroup bossGroup = new NioEventLoopGroup(1); 
     EventLoopGroup workerGroup = new NioEventLoopGroup(); 

     try { 
      SelfSignedCertificate ssc = new SelfSignedCertificate(); 
      sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); 
      ServerBootstrap b = new ServerBootstrap(); 
      b.group(bossGroup, workerGroup) 
       .channel(NioServerSocketChannel.class) 
       .handler(new LoggingHandler(LogLevel.INFO)) 
       .childHandler(new WebSocketServerInitializer(sslCtx)); 

      Channel ch = b.bind(PORT).sync().channel(); 

      System.out.println("Open your web browser and navigate to " + 
        "http://127.0.0.1:" + PORT + '/'); 

      ch.closeFuture().sync(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } finally { 
      bossGroup.shutdownGracefully(); 
      workerGroup.shutdownGracefully(); 
     } 

    } 

} 

WebSocketServerInitializer 소스 코드 :

<html> 
    <head> 

     <script type="text/javascript"> 
     // Let us open a web socket 
     var ws = null; 
     function WebSocketTest() 
     { 
      if ("WebSocket" in window) 
      { 
       alert("WebSocket is supported by your Browser!"); 

       // Let us open a web socket 
       ws = new WebSocket("wss://localhost:4466/websocket"); 
       ws.onopen = function() 
       { 
        // Web Socket is connected, send data using send() 
        ws.send("Message to send"); 
        alert("Message is sent..."); 
       }; 

       ws.onmessage = function (evt) 
       { 
        var received_msg = evt.data; 
        alert(received_msg); 
        //alert("Message is received..."); 
       }; 

       ws.onclose = function() 
       { 
        // websocket is closed. 
        alert("Connection is closed..."); 
       }; 

       window.onbeforeunload = function(event) { 
        socket.close(); 
       }; 
      } 

      else 
      { 
       // The browser doesn't support WebSocket 
       alert("WebSocket NOT supported by your Browser!"); 
      } 
     } 
     </script> 

    </head> 
    <body> 

     <div id="sse"> 
     <a href="javascript:WebSocketTest()">Run WebSocket</a> 
     </div> 
    </body> 
</html> 

I :이 내 HTML 코드

public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> 
{ 
    private static final String WEBSOCKET_PATH = "/websocket"; 
    private final SslContext sslCtx; 
    public WebSocketServerInitializer(SslContext sslCtx) { 
     this.sslCtx = sslCtx; 
    } 
    @Override 
    public void initChannel(SocketChannel ch) throws Exception { 
     ChannelPipeline pipeline = ch.pipeline(); 
     pipeline.addLast(sslCtx.newHandler(ch.alloc())); 
     pipeline.addLast(new HttpServerCodec()); 
     pipeline.addLast(new HttpObjectAggregator(65536)); 
     pipeline.addLast(new WebSocketServerCompressionHandler()); 
     pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true)); 
     // pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH)); 
     pipeline.addLast(new WebSocketFrameHandler()); 
    } 
} 

입니다 Chrome 브라우저를 사용하여 페이지를 탐색하고 웹 페이지의 링크를 클릭하면 다음 메시지가 표시됩니다. ': // localhost를 : WSS 4466/웹 소켓'에

웹 소켓 연결, 여기에 몇 가지 논의에 따르면 순 :: ERR_INSECURE_RESPONSE

및 그물코 웹 소켓의 샘플 코드 : 연결 설정에 오류 실패 wss는 HTTPS에 의해 전달되어야합니다. 내 웹 페이지에 다음과 같은 자바 스크립트 문을 변경할 때 :

ws = new WebSocket("wss://localhost:4466/websocket"); 

ws = new WebSocket("wss://echo.websocket.org"); 

에 그것은 잘 작동합니다. 그것은 혼란 스럽습니다. 왜 사이트 echo.websocket.org는 https 없이도 작동 할 수 있습니까? 왜 내 서버는 할 수 없습니까? 내 서버 소스 코드에 누락 된 것이 있습니까?

PS : 다음 URL에서 볼 수있는 echo.websocket.org 예 : 브라우저가 그것이 안전하지 감지하기 때문에, 당신의 웹 소켓 서버에 연결하는 데 실패

http://jsbin.com/muqamiqimu/edit?js,console

답변

0

.

브라우저가 서버에 연결을 시도하면 SSL 인증서를 확인하기 때문에 이런 현상이 발생합니다. 이 인증서는 기본적으로 서버가 localhost에 대한 신뢰할 수있는 서버라고 주장하는 증거입니다.

귀하의 서버가 인증서로 주장합니다. 귀하의 경우 자체 서명 된 것은 기본적으로 SelfSignedCertificate 클래스이며, "example.com"이라고 주장하고 있습니다.

  • 브라우저가 localhost에 연결하지만, 브라우저가 가지고 인증서의 서명자를 신뢰하지 않는 한
  • example.com 대신 localhost에 대한 인증서를 얻는, 그것을 가져옵니다

    이 2 문제를 생성 인증서를 만들어서 거부 당하게하는 권한.,

    유효한 인증서를 가져 오기와 서버 이것은 생산을위한 권장 솔루션이 될 것입니다, 당신은 당신의 유효한 인증서를 얻을 어디에 따라

    에서 응용 프로그램을 호스팅 :

는이 문제를 해결하기 위해 여러 가지 방법이 있습니다 그것은 돈을 요 할지도 모르고 다.

바이 패스 인증서 경고 수동으로 인증서 경고 건너 뛸 수 있으며, 기본적으로 이것은 당신이 구글 크롬을 구성 브라우저

를 다시 시작까지, 인증서 규칙에 대한 1 시간 예외를 추가 http://localhost:4466/로 이동하여

localhost에 대해 유효하지 않은 인증서를 받아 들일 수 있습니다.

이것은 안전하지는 않지만 (모든 인증서 유효성 검사를 끄지 않는 것은 안전하지는 않지만) 개발 컴퓨터에서 ssl을 테스트하는 좋은 방법 일 수 있습니다.

chrome : // flags/# allow-insecure-localhost로 이동하여 해당 옵션을 켜면 localhost에 대한 ssl 유효성 검사를 사용할 수 있습니다. 이 옵션을 사용할 때 new SelfSignedCertificate("localhost"); 생성자를 호출하여 인증서 도메인을 localhost으로 설정해야 할 수도 있습니다.

+0

설명해 주셔서 감사합니다. –

관련 문제