Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Slow Server
require 'eventmachine'
require 'socket'
$port = 9595
$connections = []
$timer_i = 3
class SlowServerConnection < EventMachine::Connection
def initialize(*args)
super(*args)
end
def post_init
@port, @ip = Socket.unpack_sockaddr_in(get_peername())
@state = 'NEW'
puts "#{self.mytag} Received Connection"
end
def receive_data(data)
@client_data ||= String.new
@client_data << data.to_s
handle_state
# If we have received header, lets send response slowly
@timer = EventMachine::PeriodicTimer.new($timer_i) do
#puts "Timer Trigger"
self.handle_state
end if @state != 'NEW'
end
def unbind
$connections.delete(self)
@timer.cancel unless @timer.nil?
puts "#{self.mytag} Connection Closed"
end
# HTTP specific (GET only)
def handle_state
case @state
when 'NEW'
if @client_data.index("\r\n\r\n")
puts "#{self.mytag} Request received"
@state = 'HEADER_SENDING'
end
when 'HEADER_SENDING'
@header_index ||= 0
puts "#{self.mytag} Sending Header (#{@header_index})"
send_data(response_header(@header_index))
@header_index += 1
@state = 'DATA_SENDING' if response_header(@header_index).nil?
when 'DATA_SENDING'
puts "#{self.mytag} Sending data"
send_data("A\n")
end
end
def response_header(index)
[
"HTTP/1.1 200 OK\r\n",
"Server: Apache\r\n",
"Content-Length: 204800\r\n",
"Content-Type: image/jpeg\r\n",
"\r\n"
][index]
end
def mytag
"T:#{$connections.size} M:#{@ip}:#{@port}:: "
end
end
EventMachine.run do
EventMachine.start_server('0.0.0.0', $port, SlowServerConnection) do |connection|
$connections << connection
end
puts "Server started on #{$port}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.