Jump to content

ruby on rails? web dev's? spoon feed me...


Recommended Posts

ruby on rails

so, im updating this post... server sent events is the new subject... with use of actioncontroller::live i can do live streaming of data with my web browser...

ill post some example code that has allowed me to run a linux application on my web server, stream each line as live output to the web browser...

when the command completes the page will respond with a DONe message...

it was a little tricky finding exmaples that worked well enough to build off...


require 'open3'
class MessagingController < ApplicationController
	include ActionController::Live
  def send_message
    response.headers['Content-Type'] = 'text/event-stream'
    #response.stream.write "data: #{l.chomp.to_json}\n\n"
    #run a application, until it finishes
    Open3.popen3("ping -c 10 google.com"){|i,o,t,p| 
    	while l=o.gets
    		response.stream.write "data: #{l.chomp.to_json}\n\n"

    	#kill the process on completion
    	response.stream.write "data: kill_stream\n\n"
    rescue IOError
    	puts "error"
    rescue ClientDisconnected
    	puts "he discconected"

this will run `ping -c 10 google.com` and send each line to the web browser.

when the execution completes, this controller will send the client a kill_stream message.

here is a index file that will connect to the action controller and display the stream as it happens...

there is a #progress id and a #Kill id... each message will show in the appropriate div...


<div class="container-fluid">
<div class="panel panel-default">
	<div class="panel-body">
		<div id="kill"></div>

<hr />

<div class="panel panel-default">
	<div class="panel-body label-success">
		<div id="progress"></div>

<script type="text/javascript">
  jQuery(document).ready(function() {
    setTimeout(function() {
      var source = new EventSource('/messaging');
      function eventLogger(event){
        if (event.data == 'kill_stream') {
        	$("#kill").append("DONE.." + "<br>");
        } else {
        	$("#progress").prepend(event.data + "<br>");

      source.onmessage = eventLogger;
    }, 10);

and you need to modify your routes.rb


root 'messaging#index'
get 'messaging' => 'messaging#send_message'
Edited by i8igmac
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...