开发者

Ruby tcpserver client server

开发者 https://www.devze.com 2023-02-17 20:55 出处:网络
I hav开发者_开发问答e an application that I am coding to have the logging info be sent over tcpsocket to a server and have a monitor client connect to the server to view the logging data .So far i am

I hav开发者_开发问答e an application that I am coding to have the logging info be sent over tcpsocket to a server and have a monitor client connect to the server to view the logging data . So far i am able to get to the stage where the info is sent to the server however I need some thoughts on how to go about the next stage. Using Ruby tcpsever what methodologies can I use to have the server resend the incoming data to a client? How can I have data stored across threads?

require "socket"  

server_socket = TCPServer.new('localhost', 2200)  

loop do  
  # Create a new thread for each connection.
  Thread.start(server_socket.accept) do |session|

    # check if received is viewer request
    line = session.gets
    if line =~ /viewer/
      @filter = line[/\:(.*?)\:/]
      session.puts "Listining for #{filter}"

      loop do
        if (log = ### need input here from logging app ###)
          # Show if filter is set for all or cli matches to filter
          if @filter == ':all:' || log =~ /\:(.*?)\:/
            session.puts log
          end

          # Read trace_viewer input. 
          if session.gets =~ /quit/
            # close the connections
            session.puts "Closing connection. Bye!"
            session.close
            break
          end
        end
      end
    end
  end  
end


With clients connecting to the server it sounds like a typical client/server configuration, with some clients sending data, and others requesting it. Is there any reason you don't use a standard HTTP client/server, i.e., a web server, instead of reinventing the wheel? Use Sinatra or Padrino, or even Rails and you'll be mostly finished.

How can I have data stored across threads?

Ruby's Thread module includes Queue, which is good for moving data around between threads. The document page has an example which should help.

The same ideas for using a queue would apply to using tables. I'd recommend using a database to act as a queue for your use, rather than do it in memory. A power outage, or app crash will lose all the data if it's an in-memory queue and the clients haven't retrieved everything. Writing and reading a database means the data would survive such problems.

Keep the schema simple, provide a reasonable index on it, and it should be fast enough for most uses. You'll need some housekeeping code to keep the database clean, but that's easy using SQL, or an ORM like Sequel or ActiveRecord.

0

精彩评论

暂无评论...
验证码 换一张
取 消