我正在使用MAMP服务器上的CodeIgniter开发一个应用程序(用于开发,实时它将在LAMP上)。我正在尝试为聊天服务器添加socket.io的实时功能,但我遇到了一些问题。我有socket.io和MAMP独立运行,但我不能让我的客户端与我的服务器通信。
server.js:
// Get the Socket.io module
var io = require('socket.io');
console.log ( 'Chat Server started' );
// Create a Socket.IO instance, listen on 8084
var socket = io.listen(8084);
// Add a connect listener
socket.on('connection', function(client){
console.log ( "Server Connected" );
});
我的客户端脚本(socket.io.js加载正常,我的控制台在加载页面时说“debug:serve static content”):
<script src="http://localhost:8084/socket.io/socket.io.js"></script>
<script type="text/javascript">
// Create SocketIO instance, connect
var socket = new io.Socket('localhost',{
port: 8084
});
socket.connect();
socket.on ( 'connect', function () { console.log ( 'Client connected' ); } );
</script>
启动node.js文件后,我在控制台中看到了这个:
Chat Server started
info - socket.io started
加载客户端后(将我的浏览器指向http://localhost:8888 - MAMP的默认端口),我没有得到任何控制台消息,而是稳定的流(大约每秒一次):< / p>
info - unhandled socket.io url
它看起来根本没有连接。此外,浏览器上的JS错误控制台中没有错误。有什么想法吗?
答案 0 :(得分:4)
运行socket.io版本0.8.5,我终于使用以下代码完成了这项工作:
server.js
var sys = require('sys'),
express = require('express'),
app = express.createServer('localhost'),
io = require('socket.io');
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);
var server = io.listen(app);
server.sockets.on('connection', function (client){
// new client is here!
client.send ( 'Now connected!' );
client.on('message', function () {
}) ;
client.on('disconnect', function () {
});
});
客户端脚本:
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="/assets/js/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var socket = io.connect('http://localhost:3000'),
text = $('#text');
socket.on('connect', function () {
text.html('connected');
socket.on('message', function (msg) {
text.html(msg);
});
});
socket.on('disconnect', function () {
text.html('disconnected');
});
});
</script>
随着一切正常运行,进入我的页面后,我看到“现已连接!”几乎立即。我也通过MAMP上的CodeIgniter提供我的页面 - 一切正常!