我正在尝试使用Socket.IO和Express进行浏览器多人游戏,但对于我来说不太清楚为什么需要Express。我在我的服务器上的应用程序中,在一个名为/游戏的文件夹中,所以要访问该应用程序,用户应该键入http://www.example.com/game而不是http://www.example.com:3000,这是本教程的用法。我知道这是更多的Apache 2 VirtualHost配置文件的问题,但我不知道在哪里发布它。 这里是我的实际.conf文件在Apache服务器上运行NodeJS
# /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
ServerAdmin [email protected]
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>
实际上,当用户通过该端口(http://www.example.com:3000)输入网址进入,服务器返回像“用户连接”,但是当我通过写日志键入URL我想(http://www.example.com/game),那么它不会返回它让我发疯的任何消息...... index.js代码:
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');
});
的index.html代码:
<!doctype html>
<html>
<head>
<title>Socket.IO App</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font: 13px Helvetica, Arial;
}
form {
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}
form input {
border: 0;
padding: 10px;
width: 90%;
margin-right: .5%;
}
form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}
#messages {
list-style-type: none;
margin: 0; padding: 0;
}
#messages li {
padding: 5px 10px;
}
#messages li:nth-child(odd) {
background: #eee;
}
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function() {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
</body>
</html>
在此先感谢。
编辑另外,我检查浏览器控制台,同时通过example.com/game访问,它说没有找到socket.io.js文件,但是当进入另一种方式它确实加载文件...
希望这会有所帮助:http://www.codingtricks.biz/run-nodejs-application-apache/ –
嗨@MirzaSisic谢谢你的回答!它实际上帮了我,但我已经看到了那篇文章,它并没有解决我的问题。现在我可以运行我的应用程序并通过example.com:3000访问它,但我希望能够使用example.com/game进行访问。实际上,它们都会将我返回到正确的页面,但是通过example.com/game输入时,它不会加载socket.io脚本(404),并且服务器不会以“连接的用户”的形式返回任何消息。再次感谢! – Marcos
当找不到socket.io时,使用它记录的URL是什么?并确认这是否正确的URL到您的套接字文件 –