app/views/home/index.html.erb 代码如下
<h2>Recently updated posts</h2>
<table>
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
<% @posts.each do |post| %>
<tr>
<td><%= post[:title] %></td>
</tr>
<tr>
<td><%= post[:id] %></td>
</tr>
<% end %>
</tbody>
</table>
<script type="text/javascript">
$(function(){
var source = new EventSource('/home/aaa');
var message;
source.addEventListener("upstream", function(e){
message = e.data;
alert(message);
}, false );
})
</script>
require 'server_sent_event/sse'
class HomeController < ApplicationController
include ActionController::Live
def index
@posts = RecentPosts.list
end
def aaa
response.headers['Content-Type'] = 'text/event-stream'
# sse = Sse.new(response.stream)
# # RecentPosts.list.each do | r |
# # puts r[:title]
# # end
# sse.write({name: 'Test'}, event: "event_name")
# render nothing: true
# begin
# rescue IOError
# # Client Disconnected
# ensure
# sse.close
# end
response.stream.write('event: upstream')
response.stream.write('data: pricess started')
render nothing: true
rescue IOError
logger.info 'stream close'
ensure
response.stream.close
end
end
监听器中监听不到数据。。。