【发布时间】:2019-05-31 02:37:54
【问题描述】:
我正在使用 Nginx 服务器运行 node.js 和 socket.io。 这是我的 /etc/nginx/conf.d/site.conf:
server {
listen 443;
server_name localhost;
client_max_body_size 20M;
location /websocket/ {
root ChatWithSocket;
index index.html index.htm index.nginx-debian.html;
proxy_pass http://localhost:4000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
这是我的 /ChatWithSocket/index.js:
var express = require('express');
var socket = require('socket.io');
// App setup
var app = express();
var server = app.listen(4000, function(){
console.log('listening for requests on port 4000,');
});
// Static files
app.use(express.static('public'));
//Socket setup
var io = socket(server);
io.on('connection', function(socket){
console.log('made socket connection', socket.id);
//Show diconnect log when we refresh page
socket.on('disconnect', function(){
console.log('The socket disconnected');
});
// Handle chat event
socket.on('chat', function(data){
// console.log(data);
io.sockets.emit('chat', data);
});
// Handle typing event
socket.on('typing', function(data){
socket.broadcast.emit('typing', data);
});
});
这是我的 /ChatWithSocket/public/chat.js:
// Make connection
var socket = io.connect('http://localhost:4000');
// Query DOM
var message = document.getElementById('message'),
handle = document.getElementById('handle'),
btn = document.getElementById('send'),
output = document.getElementById('output'),
feedback = document.getElementById('feedback'),
chatWindow = document.getElementById('chat-window');
......................................................
T
我无法使用地址https://localhost/websocket/.I 运行,我遵循了许多关于 Nginx + WebSocket 的在线指南,但我不知道我在哪里犯了错误。请帮帮我。
【问题讨论】:
-
在您的客户端中,您不是在尝试连接到本地主机吗?而服务器托管在 40.115.176.82?同样在 nginx 中,您已配置为仅将前缀为 /websocket/ 的 url 路由到您的 socketio 服务器。尝试在客户端
var socket = io('https://40.115.176.82', {path: ' /websocket/'});上正确设置前缀和服务器。另请阅读stackoverflow.com/questions/9729308/socket-io-connection-url
标签: javascript node.js nginx websocket