在项目长时间缺席后尝试将socket.io/nodejs集成到页面中时,我遇到了很多问题,试图为它设置服务器后端。通过nvm安装节点,(节点版本0.12.1
,socket.io版本1.3.5
)
当我尝试运行服务器时(通过简单的node receiver.js
),我无法连接到/socket.io/socket.io.js
文件中的index.php
,如下面提供的代码所示:< / p>
index.php (客户端)
<!-- in html > head -->
<script src="/socket.io/socket.io.js"></script> <!-- Problem here -->
<script>
if (typeof io === 'undefined') {
console.error("Error connecting to nodejs backend! Expect some errors");
}
var socket = io();
</script>
<script src="/assets/js/selector.js"></script>
receiver.js (服务器端)
console.log('loading requirements...');
var io = require('socket.io')(80);
var net = require('net');
var mysql = require('mysql2');
console.log('connecting to mysql...');
var connection = mysql.createConnection({
user: '', //removed
password: '', //removed
database: '', //removed
stream: net.connect(3306, "codelanx.com")
});
var sent = {};
console.log('listening...');
io.sockets.on('connection', function(socket) {
//socket.io methods, etc...
selector.js (客户端)
//...
jQuery(document).ready(function($) {
socket.emit('requestName');
//...
}
在服务器端,打印所有日志记录语句(转到listening...
)。我一直在为require('socket.io')
配置调用线,这几乎是所有可以想象的方式,但仍然无法进行连接。我错过了什么吗?
答案 0 :(得分:3)
您需要创建http服务器并将其作为参数传递给socket.io,而是将80作为参数传递:
var server = require('http').createServer();
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('event', function(data){});
socket.on('disconnect', function(){});
});
server.listen(80);