0

I got the idea from IP camera's where they use multipart headers to send JPEG frames but also XML for events like motion detection. The data flows one way on random moments and after some timeout a new connection must be made to the server. I have made client applications for these devices before but never with AJAX and now I'm trying to make a similar server in node.js

I know I could use socket.io but I'm just interested in using this way for now. Is it possible?

This will write the current date every second in chunk parts with a boundary and works fine in telnet.

var http = require('http');
http.createServer(function(request, response) {
    response.writeHead(200, {
        'Content-Type': 'multipart/x-mixed-replace; boundary=boundary',
        'Access-Control-Allow-Origin' : '*',
        'Connection': 'keep-alive'
    });

    setInterval(function () {
        response.write('--boundary\r\n', 'ascii');
        response.write('Content-Type: text/plain\r\n', 'ascii');
        response.write('\r\n', 'ascii');
        var date = new Date();
        response.write(date.toString() + '\r\n\r\n', 'ascii');
    }, 1000);
}).listen(8080);

AJAX connection that will log the current ready state

var url = "http://localhost:8080";      
var xhr = $.ajax({
              'url': url,
              'success' : function(html) {
                    $('body').append(html);
               }
            });

xhr.onreadystatechange = function() {
     console.log(xhr.readyState,xhr.status,xhr.responseText);
}

All I get is the ready state '4' and status '0' also in my Network tools I see a 'canceled' header error.

When I lose the multipart/x-mixed-replace and just push it down a normal HTTP connection I get multiple ready state '3' but no data.

Brmm
  • 320
  • 1
  • 2
  • 11

1 Answers1

1

jQuery almost certainly sets its own internal readystatechange handler on the XHR it creates, and you're overwriting it. Use xhr.addEventListener('readystatechange', function() { ... instead.

ebohlman
  • 14,795
  • 5
  • 33
  • 35
  • Thanks, yes of course that was a stupid mistake but unfortunately the correct way has the same undesired result. I still get a status 'canceled' in my Chrome network tools and no data. – Brmm Aug 19 '12 at 04:52