Skip to content

Instantly share code, notes, and snippets.

@tompurl
Last active December 28, 2015 03:29
Show Gist options
  • Save tompurl/7435196 to your computer and use it in GitHub Desktop.
Save tompurl/7435196 to your computer and use it in GitHub Desktop.
Cowsay Socket Server - Iteration 1
require 'socket'
module CowSay
class Server
def initialize(port)
# Create the underlying socket server
@server = TCPServer.new(port)
puts "Listening on port #{@server.local_address.ip_port}"
end
def start
# TODO Currently this server can only accept one connection at at
# time. Do I want to change that so I can process multiple requests
# at once?
Socket.accept_loop(@server) do |connection|
handle(connection)
connection.close
end
end
def handle(connection)
# TODO Read is going to block until EOF. I need to use something
# different that will work without an EOF.
request = connection.read
# The current API will accept a message only from netcat. This
# message is what the cow will say. Soon I will add support for
# more features, like choosing your cow.
# TODO - Parse the request
# Write back the result of the hash operation
connection.write process(request)
end
def process(request)
# TODO This is just painfully naive. I'll use a different
# interface eventually.
`cowsay "#{request}"`
end
end
end
server = CowSay::Server.new(4481)
server.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment