我刚刚更新了node + socket应用以使用https。花费了一段时间,但是我现在在这里可以使用nginx,node.js,socket.io配置。它很好用,但是我的问题是,是否可以配置服务器端,以便客户端不需要提交path
参数,或至少将其作为url的一部分?我希望能够仅向用户提供要使用的网址,例如https://mywebsite.com/apiPath/myNamespace
。
当前:
NGINX配置:
upstream websocket1 {
server 127.0.0.1:3000;
}
server {
listen 80;
listen [::]:80;
server_name mywebsite.com;
return 301 https://mywebsite.com$request_uri;
}
server {
listen 443 ssl;
server_name mywebsite.com;
ssl_certificate this.crt;
ssl_certificate_key this.pem;
location /apiPath/ {
proxy_pass http://websocket1/socket.io/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
服务器:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
http.listen(port);
var nsp = io.of('/myNamespace');
nsp.on('connection', function(socket) {
console.log('connected!');
});
客户:
var socket = require('socket.io-client')(https://mywebsite.com/myNamespace, {path: '/apiPath'});
谢谢!
答案 0 :(得分:0)
您可以选择不使用path参数,但是路径是名称空间。如果不提供,则仅使用/
的命名空间。如果只需要一个名称空间,那应该没问题。只需在您的.of()
调用中指定io
,您只需执行io.to()
,它将使用默认的名称空间
答案 1 :(得分:0)
好吧,我找到了解决问题here的方法。使用此新设置,我不需要传递main-compiled.js?v=<?php echo time()?>"
参数,可以将名称空间用作我的url的一部分。我修改后的设置如下:
NGINX配置:
path
服务器:
upstream websocket1 {
server 127.0.0.1:3000;
}
server {
listen 80;
listen [::]:80;
server_name mywebsite.com;
return 301 https://mywebsite.com$request_uri;
}
server {
listen 443 ssl;
server_name mywebsite.com;
ssl_certificate this.crt;
ssl_certificate_key this.pem;
location ~(myNamespace|socket\.io).*$ {
proxy_pass http://websocket1;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
客户:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
http.listen(port);
var nsp = io.of('/myNamespace');
nsp.on('connection', function(socket) {
console.log('connected!');
});