socket.io没有为客户端连接

时间:2014-06-28 08:25:49

标签: node.js socket.io

这是使用node.js和socket.io的简单聊天应用。这个应用程序在我的本地计算机上运行良好但在我上传到服务器时不起作用:请look at my code on remote server and the problem

以下是客户端的代码段:

<script type="application/javascript">
    var socket = io.connect();

    eventHandler(socket);

    function eventHandler(socket) { 
        socket.on('connect', function(){
            socket.emit('adduser', prompt("What's your name?"));
        });
        socket.on('error', function () {
            console.log("Connection error"); //It works after a few second with error
        });
    }

    $(document).ready(function(){
       .....
    });
</script>

3 个答案:

答案 0 :(得分:0)

在远程服务器上看起来像是安装了Socket.IO 0.9.16(它不是最新的)。如果您根据new documentation编写代码,这可能是它无法按预期工作的原因。

尝试将Socket.IO升级到1.0

答案 1 :(得分:0)

这项改变对我有用: 你写了这个方法:

var socket = io.connect();

感谢another help page,我将此方法更改为:

var socket = io.connect('http://localhost:8080');

您可以将“localhost”替换为您用于访问服务器的任何IP地址。

另外,以防万一 - 如果还没有,在app.js文件中包含服务器上的连接通知会很有用。我的看起来如下:

var fs = require("fs")
, http = require("http")
, socketio = require("socket.io");

var server = http.createServer(function(req, res) {
	res.writeHead(200, { "Content-type": "text/html"});
	res.end(fs.readFileSync(__dirname + "/index.php"));
}).listen(8080, function() {
	console.log("Listening at http://localhost:8080");
});

socketio.listen(server).on("connection", function(socket) {
	console.log("CONNECTED");
	socket.on("message", function(msg) {
		console.log("Message received: ", msg);
		socket.broadcast.emit("message", msg);
	});
});

如果他们有与您的问题更密切相关的内容,您还可以看到the help page I linked to

答案 2 :(得分:-1)

您的页面似乎对我有用。在执行脚本之前,请确保您的页面已完全加载。这是通过使用window.onload完成的,如下所示:

<script>
    window.onload = function() {
        //Your code here
    }
</script>
相关问题