我正在尝试使用Socket.IO和Express制作浏览器多人游戏,尽管我不太清楚为什么需要Express。我在我的服务器中有一个名为/ game的文件夹中的应用程序,因此要访问应用程序,用户应该键入http://www.example.com/game而不是http://www.example.com:3000,这就是教程的工作方式。我知道这更像是一个Apache 2 VirtualHost配置文件问题,但我不知道在哪里发布它。 这是我的实际.conf文件
public string Price
{
get
{
return $"{(double.Parse(Market) / double.Parse(Average)).ToString()}";
}
set
{
price = value;
OnPropertyChanged(nameof(Price));
}
}
实际上,当用户通过键入带端口(http://www.example.com:3000)的URL进入时,服务器返回一条日志消息,例如“用户连接”但是当我输入时输入我想要的URL({{3} })然后它不会返回任何让我发疯的消息...... index.js代码:
# /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
ServerAdmin admin@example.com
DocumentRoot /var/www/example.com/public_html
ServerName example.com
ServerAlias www.example.com
ProxyPreserveHost On
ProxyPass /game http://www.example.com:3000
ProxyPassReverse /game http://www.example.com:3000
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
index.html代码:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg){
onsole.log('message: ' + msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
提前致谢。
编辑:此外,我通过example.com/game访问时检查了浏览器控制台,它说找不到socket.io.js文件,但是当输入另一种方式时正确加载文件......
答案 0 :(得分:1)
在客户端,指定socket.io客户端的path
字段:
var socket = io('http://www.example.com', {
'path': '/game/socket.io'
});
或:
var socket = io(window.location.origin, {
'path': window.location.pathname + '/socket.io'
});
在您的apache配置中,还要添加ws
重写规则来路由websocket流量,您需要proxy
,proxy_http
,proxy_wstunnel
和rewrite
模块:
RewriteEngine On
RewriteCond %{HTTP:Connection} Upgrade [NC]
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteRule /game/(.*) ws://www.example.com:3000/$1 [P,L]
ProxyPass /game http://www.example.com:3000
ProxyPassReverse /game http://www.example.com:3000
您可以使用docker找到here示例项目来重现您的配置(node app + apache reverse proxy)