0

I am experimenting with HTML5 and node.js. I have tested out Server Sent Events and they worked fine(Refering to this example).

Next I tried replying to a button press with an SSE. On pressing the "Increment" button I pick a number from a text box and pass it to the server using a GET message. The server will then respond with an event containing the incremented number. The eventListener will then update the text box with the received number. I have also added a "Message area" on the HTML page to log messages.

That was the plan. But when I click the button the browser shows a "downloading" operation is in progress in the bottom of the window but it never completes and the result is not updated on the screen nor is the message displayed in the bottom of the page.

The events work fine when i send them at the load of the page. But when I send it in response to a GET message the HTML page doesn't show any response.

Here is the HTML section.

<form action="/upload" method="get">
<p>Set the temperature and click on send</p>
<input name="temperature" id="TemperatureBox" type="text" value = "33" />
<button type="submit" onclick="form.action='http://localhost:8888/Increment'">Increment</button>

I have added handlers for messages and for a "temperature event" which will update the Temperature box

var source = new EventSource('/events');

source.addEventListener('message', function(e) {
  //code to display message
}, false);

source.addEventListener('TemperatureValueUpdate', function(e) {
        AddLog('TemperatureValueUpdate Listener >> lastEventID: ' + (e.lastEventId || '--') +
               ', e.data: ' + e.data
        + 'Current value of text box: ' +  document.getElementById('TemperatureBox').value);
        document.getElementById('TemperatureBox').value= e.data;

}, false);

In the node.js script i am sending a message and a TemperatureValueUpdate

function constructTemperature(response, id, data) {
console.log("Sending Temperature event");
//  response.write('id: ' + (new Date()).toLocaleTimeString()+ '\n');
 // response.write("data: " + 'Teperature event sent '+ '\n\n');

response.write('event: ' + 'TemperatureValueUpdate' + '\n');
response.write('id: ' + id + '\n');
response.write("data: " + data + '\n\n');

console.log("Finished Temperature event"); }

I have also responded to the "/events" URL on the page load with a 200 reply:

response.writeHead(200, {'Content-Type': 'text/event-stream','Cache-Control': 'no-cache', 'Connection': 'keep-alive' });

I have even tried the following

  • Sending a 202/204 response before sending the events
  • sending a response.end() before/after sending the events
  • Sending a 'Content-Type': 'text/event-stream' before each event

But they don't produce the desired result. What am I doing wrong here?

4

1 回答 1

0

听起来您在提交表单时正在调用constructTemperature() 函数。如果是这种情况,您与 EventSource 的连接不同。因此,您需要将数据存储在服务器上的某个位置返回给客户端,并在源自 EventSource 的请求中调用constructTemperature()。

于 2012-07-06T06:46:55.077 回答