1

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

我有它,所以我可以与 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
}
4

1 回答 1

1

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

...
server = TCPServer.open(listen_port)
client = server.accept # <- moved out of the loop
loop {                                  
  f.puts "#{Time.now} Client Connected"
...
于 2012-09-24T19:26:53.540 回答