Ruby - 在网络套接字上接收多行

时间:2012-09-24 04:36:45

标签: ruby sockets

我正在编写一个基本的网络日志记录脚本,客户端可以连接到我的服务器套接字,从套接字读取的所有数据都将写入文件。

我有它所以我可以连接telnet并且第一行(在按下enter之前)被写入文件,但后续行没有被写入。我需要更改什么才能使其正常工作?

我还希望能够将多个侦听套接字写入同一个文件 - 有没有办法在没有多线程的情况下执行此操作?

log_path ||= "./network-logs"
listen_port ||= 2509
minute_buffer = {now: Time.now, buffer: "" }
current_time = Time.now
current_date = Date.today.to_s
client = nil
Dir.mkdir(log_path) unless File.exists?(log_path)
f = File.new("#{log_path}/#{current_date}.txt", 'w')

def short_time
  "%02d" % Time.now.hour.to_s + ':' + 
  "%02d" % Time.now.min.to_s + ':' + 
  "%02d" % Time.now.sec.to_s
end

server = TCPServer.open(listen_port)
loop {                                  
  client = server.accept                
  f.puts "#{Time.now} Client Connected"
  puts "#{Time.now} Client Connected"
  current_time = Time.now               
  if minute_buffer[:now].min != Time.now.min 
    f.puts "##### Minute summary for #{minute_buffer[:now].to_s}: #{minute_buffer[:min]} :"
    puts "##### Minute summary for #{minute_buffer[:now].to_s}: #{minute_buffer[:min]} :"
    f.puts "##### #{minute_buffer[:buffer]}"
    minute_buffer[:now] = Time.now
    minute_buffer[:buffer] = ""
  end
  data = client.gets
  f.puts short_time + "  : " + data.to_s
  puts short_time + "  : " + data.to_s
  minute_buffer[:buffer] = minute_buffer[:buffer] + data.to_s
  if current_date != Date.today.to_s
    f.close
    current_date = Date.today.to_s
    f = File.new("#{log_path}/#{current_date}.txt", 'w')
  end
}

1 个答案:

答案 0 :(得分:1)

您必须将client = server.accept行移出循环:

...
server = TCPServer.open(listen_port)
client = server.accept # <- moved out of the loop
loop {                                  
  f.puts "#{Time.now} Client Connected"
...