创建了一个node.js应用程序并使用nginx反向代理进行配置。该应用程序工作正常,直到我用nginx配置它。但是然后在nginx应用程序中能够连接到服务器但连接不会还原为客户端。但是服务器在连接时打印日志。代码片段如下。我忘了提到我使用socket-io和ember.js
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
io.sockets.on('connect', function (socket) {
console.log('------------->> Client Conected !!');
socket.on('message', function (msg) {
onMessage(msg);
});
function onMessage(msg) {
console.log('------------->> client msg - '+msg);
}
socket.on('disconnect', function () {
console.log("------------->> Client disconected !!");
});
});
console.log("server started @ 3000");
import Ember from 'ember';
export default Ember.Controller.extend({
socketIOService: Ember.inject.service('socket-io'),
init: function() {
this._super.apply(this, arguments);
var socket = this.get('socketIOService').socketFor('http://nginx.domain.com/socketio/server');
socket.on('connect', function() {
console.log("connected");
socket.send('Hi Server');
socket.on('message', this.onMessage, this);
}, this);
},
onMessage: function(data) {
console.log(data);
}
});
这很好,直到nginx发挥作用。但仍设法配置如下
http {
upstream node {
server ip-node-app:3000;
}
server {
listen 80;
server_name nginx.domain.com;
location / {
root html;
index index.html index.htm;
}
location /socketio/server {
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_set_header X-NginX-Proxy true;
proxy_buffers 8 32k;
proxy_buffer_size 64k;
proxy_pass http://node;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /socket.io {
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_set_header X-NginX-Proxy true;
proxy_buffers 8 32k;
proxy_buffer_size 64k;
proxy_pass http://node;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
}
一旦客户端向服务器发出请求,我就会看到console.log打印
"&------------- GT;>客户端被收集!!"
但是客户端根本没有从服务器得到任何响应(这意味着客户端无法连接到服务器但服务器接收到客户端连接的请求)。我在这里失踪了什么?
答案 0 :(得分:0)
server {
server_name app.domain.com;
location / {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://socket_node;
}
}
此配置应该有效。
来源:https://www.nginx.com/blog/nginx-nodejs-websockets-socketio/