I have a error with nodejs 0.10.2 + express 3.x + socket.io 0.9.11
nodejs : v0.10.2 and express 3.x and socket.io 0.9.11
I just try sample code on the socket.io like lelow.
http.js708 throw new Error(can't set headers after ther are sent)
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' }); });
than I have a error message like on the picture.
First u 've to check the connection was established r not after that u continue ur code
here some sample code
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..')
})
我已经改变了socket.io 0.9.11到0.9.13比它的工作。
Check handler function in server side code. You are sending response muliple times, thats why it was giving error as headers sent already, as response was already sent & you are sending it again. Correct the code as below.
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);
}
});
}
链接地址: http://www.djcxy.com/p/44808.html
上一篇: Sailsjs套接字IO