2017-11-26 12 views
0

나는 우분투 14.04 LTS 기계에 간단한 nodejs를 가지고있다. 클라이언트가 localhost : 3000에 있더라도 nginx 또는 passenger를 ws : // localhost : 8443/helloworld에 대한 호출을 수신하도록 구성하려면 어떻게합니까? 내 정적/index.html을 파일에서NGINX listen websocket 클라이언트의 전화

var path = require('path'); 
var ws = require('ws'); 
var express = require('express'); 
var minimist = require('minimist'); 
var url = require('url'); 
var fs = require('fs'); 
var http = require('http'); 
var app = express(); 

app.use(express.static(path.join(__dirname, 'static'))); 

/* ======================================== */ 
/* =======       ======== */ 
/* ======= WEBSOCKETS SERVER ======== */ 
/* =======       ======== */ 
/* ======================================== */ 

var asUrl = url.parse("http://localhost:8443/"); 
var port = asUrl.port; 
var server = http.createServer(app).listen(port, function() { 
    console.log('********** WS HTTP SERVER STARTED********** '); 
}); 

var wss = new ws.Server({ 
    server : server, 
    path : '/helloworld' 
}); 

/* ======================================== */ 
/* ========= WSS ON CONNETION ======== */ 
/* ======================================== */ 
wss.on('connection', function(ws) { 

    console.log('**** CONNECTION RECEIVED =D'); 
    ws.send(JSON.stringify("WELCOME FROM SERVER =D")); 

    ws.on('message', function incoming(data) { 
     console.log('********** RECEIVED MSG '+data); 
     ws.send(JSON.stringify(data)); 
    }); 
}); 
/* ======================================== */ 

내가 가진 :

server.js처럼 보이는

<!-- ======================================= --> 
<!-- ==========  CSS  =========== --> 
<!-- ======================================= --> 
    <style> 
    p { line-height:18px; } 
    div { width:500px; margin-left:auto; margin-right:auto;} 
    #content { padding:5px; background:#ddd; border-radius:5px; 
       overflow-y: scroll; border:1px solid #CCC;margin-top:10px; height: 160px; } 
    #input_hello { border-radius:2px; border:1px solid #ccc; margin:10px; padding:5px; width:50%; float:left;} 
    #status { width:88px;display:block;float:left;margin-top:15px; } 
    </style> 


<!-- ======================================= --> 
<!-- ========== JS FOR WEBSOCKET =========== --> 
<!-- ======================================= --> 
<script type="text/javascript"> 
    $(document).ready(function() { 
    //-- ======================================= --// 

      // ======================== // 
      // ====== CONNECTION ====== // 
      // ======================== // 

      var content = $('#content'); 
      var message = $('#input_hello input[type="text"]').val(); 
      var ws = new WebSocket('ws://localhost:8443/helloworld'); 

      ws.onopen = function() { 
       alert("YOU ARE CONNECTED WITH WSS!!!!"); 
      }; 

      // ======================== // 
      // ====== ON KEY PRESS ==== // 
      // ======================== // 

      $("#input_hello").keydown(function(event) { 
       // ======= IF IS ENTER ===== // 
       if (event.keyCode == 13) { 
        ws.send(message); 
        return false; 
       } 
       // ======================== // 
      }); 

      // ======================== // 
      // ====== WS MESSAGE ====== // 
      // ======================== // 
      ws.onmessage = function(msg) { 
       alert("RECEIVED MESSAGE WITH WSS!!!!"); 
       addMessage(msg.data); 
      } 

      // ======================== // 
      // ==== RENDER MESSAGE ==== // 
      // ======================== // 
      function addMessage(message) { 
       content.prepend('<p><span>' + message + '</span></p>'); 
       $("#input_hello").val(""); 
      } 
    //-- ======================================= --// 
    }); 
</script> 





<!-- ======================================== --> 
<!-- ======================================== --> 
<!-- ========   HTML   ======= --> 
<!-- ======================================== --> 
<!-- ======================================== --> 
<h1>HELLO FROM EXPRESS</h1> 
<div id="content"></div> 
<div> 
    <input type="text" id="input_hello" /> 
</div> 
<!-- ======================================== --> 

이것은 내 등 /의 nginx/사이트 지원/default 파일 :

#===================# 
#==== SERVER::80 ===# 
#===================# 
server { 
     listen 80 default_server; 
     listen [::]:80 default_server; 
     #========================# 
     #==== FOR ROOT =====# 
     #========================# 
      root /home/deploy/Desktop/NODE_APP/static; 
     #========================# 
     #==== FOR PASSENGER =====# 
     #========================# 
      passenger_enabled on; 
      passenger_app_env development; 
      passenger_app_type node; 
      passenger_app_root /home/deploy/Desktop/NODE_APP; 
      passenger_startup_file /home/deploy/Desktop/NODE_APP/server.js; 
     location/{ 
       try_files $uri $uri/ =404; 
     } 
} 

#===================# 
#=== SERVER 8443 ===# 
#===================# 
server { 
     listen 8443; 
     listen [::]:8443; 

     #========================# 
     #==== FOR ROOT =====# 
     #========================# 
      root /nowhere; #========== NO NEED STATIC FILES..(ONLY WS!) 
     #========================# 
     #==== FOR WEBSOCKETS ====# 
     #========================# 
     location/{ 
      proxy_set_header X-Real-IP $remote_addr; 
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
      proxy_set_header Host $http_host; 
      proxy_redirect off; 
      proxy_pass http://localhost:8443/helloworld; 
     } 
} 

#=======================================# 
#=======================================# 

node /home/deploy/Desktop/NODE_APP/server.js을 실행하면 localhost : 3000 또는 localhost : 8443에 액세스하고 ws : // localhost : 8443/helloworld의 websocket에 의해 8443에서 실행되는 node.js 서버에 연결할 수 있습니다.

하지만 sudo service nginx start를 실행할 때, 나는 WebSocket을 Node.js를 서버가 WS에 의해 8443에서 실행 더 이상 교환 할 수 없습니다 : // localhost를 : 8443/helloworld를

가 어떻게 호출을 듣고의 nginx 또는 승객을 구성 할 수 있습니다 클라이언트가 localhost : 3000에 있더라도 ws : // localhost : 8443/helloworld?

+0

은 명시 응용 프로그램 만 웹 소켓을 통해 요청을 처리하거나 또한 몇 가지를 처리인가 포트 80 서버? 이것은 약간 단순화 될 수있는 것처럼 보이지만 확인하고 싶었습니다. –

+0

@CamdenNarzt에게 감사드립니다. 누구나 볼 수 있도록 모자를 쓴다. 나는 PORT 3000에서 실행중인 하나의 메인 서버를 가지고있다. 그리고이 명시적인 서버를 스탠드 얼론 파일로 사용하고 포트 8443 (HTTP로)에서 실행 중이며 WS 연결을 생성한다. 8443/helloworld에서. –

+0

어떻게 NGINX를 구성하여 포트 8443/helloworld에서 두 번째 서버를 청취하고, WS 데이터를 렌더링하고, HTML 페이지를 렌더링하지 않을 수 있습니다. 메인 서버 뷰를 유지합니다. –

답변

0

앱을 가질 수 없으며 nginx는 동일한 포트에서 수신 대기합니다. 다른 포트에서 websocket 연결을 청취하고 nginx를 8443에서 해당 포트로 전달하려면 앱이 필요합니다. 또한

앱에서 여러 포트를 사용하는 경우, 당신은 하나가 승객에게 필요한 "주요"하나 https://www.phusionpassenger.com/library/indepth/nodejs/reverse_port_binding.html#caveat-multiple-http-server-objects-error-http-server-listen-was-called-more-than-once

+0

Perfect! 대단히 감사합니다. @CamdenNarzt !! 공유 할 생각이 있으십니까? –