Created
December 10, 2014 07:06
-
-
Save brianstorti/ad645866668f69efb6ea to your computer and use it in GitHub Desktop.
dumb client/server socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
class Client | |
private | |
attr_reader :host, :port | |
public | |
def initialize(host, port) | |
@host, @port = host, port | |
end | |
def set(key, value) | |
request("SET #{key} #{value}") | |
end | |
def get(key) | |
request("GET #{key}") | |
end | |
private | |
def request(message) | |
client = TCPSocket.new(host, port) | |
client.write(message) | |
client.close_write | |
client.read | |
end | |
end | |
client = Client.new("localhost", "4481") | |
p client.set("name", "brian") | |
p client.get("name") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
class Server | |
def initialize(port) | |
@server = TCPServer.new(port) | |
@storage = {} | |
end | |
def start | |
Socket.accept_loop(@server) do |connection| | |
handle(connection) | |
connection.close | |
end | |
end | |
private | |
def handle(connection) | |
request = connection.read | |
connection.write(process(request)) | |
end | |
def process(request) | |
command, key, value = request.split | |
case command.upcase | |
when 'GET' | |
@storage[key] | |
when 'SET' | |
@storage[key] = value | |
end | |
end | |
end | |
server = Server.new(4481) | |
server.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment