连接拒绝节点js

时间:2014-10-25 15:17:26

标签: javascript node.js sockets

帮助我想要测试套接字的每个人,当我连接时应该出现一个警报,它可以在安装了Node js的计算机上运行,​​但不能在另一台计算机上运行。

错误:

  

无法加载资源:net :: ERR_CONNECTION_REFUSED   http://xxx.xxx.xxx.xxx:8080/socket.io/socket.io.js未被捕   ReferenceError:未定义io

代码:     服务器:

var http = require('http');
var fs   = require('fs');
var io = require('socket.io');

var server = http.createServer(function(req,res){
    res.writeHead(200,{'Content-Type' : 'text/html'});
    fs.readFile('./index.html',function(err,content){
        res.end(content);
    });

}).listen(8080);

io = io.listen(server)

io.sockets.on('connection',function(client){

client.emit('connecte');

});

客户:

<html>
<meta charset='utf-8'/>
<head>
    <title>my first page</title>
<script src="http://localhost:8080/socket.io/socket.io.js" ></script>
</head>
<body>
    <h1>It work</h1>
</body>
<script>
var socket; 

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

socket.on('connecte', function(){
        alert('You are connected');
    });

</script>
</html>

对不起语言英语不是我尝试学习的第一语言。 感谢

1 个答案:

答案 0 :(得分:1)

Socket.IO docs显示了如何将Socket.IO与内置的http服务器一起使用。比较该示例和您的代码,您可以看到您没有正确使用io。尝试这样的事情:

var http = require('http');
var fs = require('fs');
var io = require('socket.io');

var server = http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/html'});
  fs.readFile('./index.html', function(err, content) {
    res.end(content);
  });
});

io = io(server);

server.listen(8080);

io.on('connection', function(client) {
  client.emit('connected');
});

另外,在一个不相关的说明中,您可以将pipe() html文件发送到客户端,而不是先缓冲整个文件:

  res.writeHead(200, {'Content-Type': 'text/html'});
  fs.createReadStream('index.html').pipe(res);
相关问题