我正在尝试部署服务器发送的事件来替换我的应用程序中的ajax长轮询。在perl脚本中,睡眠阻止了发送流。
#!/opt/lampp/bin/perl
print "Content-Type: text/event-stream\n\n";
while(1){
print "event: server-time\n";
my $time = localtime();
print "data: $time\n\n";
}
此代码有效。但是,睡眠不起作用。只是流媒体
而不是打印它继续加载的内容。
HTML片段:
<head>
<script type="text/javascript">
function invokeSSE(){
var source = new EventSource('test.pl');
source.addEventListener('server-time', function(e) {
document.getElementById('ticker').innerHTML = e.data + '<br>';
}, false);
source.addEventListener('open', function(e) {
alert('open');
}, false);
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
alert("Connection closed");
}
}, false);
}
</script>
</head>
<body onload="invokeSSE()">
<div id="ticker" name="ticker">
[TIME]
</div>
</body>
答案 0 :(得分:1)
睡眠总是阻止,这是设计的。
你应该为此创建一个基于事件的应用程序,你可以使用Dancer,Mojolicious。
来自:http://mojolicio.us/perldoc/Mojolicious/Guides/Cookbook#Streaming_response
use Mojo::UserAgent;
# Build a normal transaction
my $ua = Mojo::UserAgent->new;
my $tx = $ua->build_tx(GET => 'http://example.com');
# Prepare body
my $body = 'Hello world!';
$tx->req->headers->content_length(length $body);
# Start writing directly with a drain callback
my $drain;
$drain = sub {
my $content = shift;
my $chunk = substr $body, 0, 1, '';
$drain = undef unless length $body;
$content->write($chunk, $drain);
};
$tx->req->content->$drain;
# Process transaction
$tx = $ua->start($tx);