I'm writing a basic network logging script where a client can connect to my server socket, and all data read from the socket will be written to file.
I have it so I can connect with telnet and the first line (before enter is pressed) is written to file, but subsequent lines are not being written. What do I need to change to make this work properly?
I also want to be able to have multiple listening sockets writing to the same file - is there a way to do this without multi-threading?
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
}