首页 文章

我有一个错误,nodejs 0.10.2表示3.x socket.io 0.9.11

提问于
浏览
1

nodejs:v0.10.2并表示3.x和socket.io 0.9.11

我只是在socket.io上尝试示例代码,如下所示 .

http.js708抛出新错误(发送后无法设置标头)

http://socket.io/#how-to-use

Server side

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

client side - index.html

var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
});

然后我在图片上有一条错误信息 .

enter image description here

3 回答

  • 0

    首先你要检查连接是否已经 Build ,而不是你继续你的代码

    这里有一些示例代码

    var app = require('express')()
      , http = require('http')
      , server = http.createServer(app)
      , io = require('socket.io').listen(server)
    
    server.listen(3000)    
    
    io.on('connection',function(socket){
      console.log('connection..')
    })
    
  • 1

    我已将socket.io 0.9.11更改为0.9.13而不是它的工作原理 .

  • 0

    检查服务器端代码中的处理函数 . 您正在发送响应多次,这就是为什么它已经发送错误作为已发送的标头,因为响应已经发送并且您再次发送它 . 更正下面的代码 .

    function handler (req, res) {
      fs.readFile(__dirname + '/index.html',
      function (err, data) {
        if (err) {
          res.writeHead(500);
          return res.end('Error loading index.html');
        } else {
          res.writeHead(200);
          res.end(data);
        }
      });
    }
    

相关问题