Computer Science Canada

Fairly simple multi-user client-server setup in Ruby

Author:  wtd [ Thu Aug 05, 2004 5:48 pm ]
Post subject:  Fairly simple multi-user client-server setup in Ruby

[mod:ca3363846a]hehe, I think this belongs here Smile [/mod:ca3363846a]

Heh... got me to thinking about how you'd write a fairly simple multi-user client-server setup in Ruby. It's not perfect by any means, but it kicks Turing all over the place on number of lines. Wink

chat_server.rb

code:
require "socket"
require "thread"

PORT = (ARGV.shift or 5535).to_i

ADMIN = ARGV.shift or "Chris"
PASSWORD = ARGV.shift or "God"

chat_server = TCPServer.new("localhost", PORT)

chat_clients = []

loop do
        Thread.new(chat_server.accept) do |chat_client|
                chat_clients << chat_client
                while line = chat_client.gets.strip
                        puts "[#{Time.now}]"
                        case line
                                when "exit as #{ADMIN} with #{PASSWORD}"
                                        puts "#{ADMIN} killed the server."
                                        exit
                                else
                                        puts line
                        end
                end
        end
end


chat_client.rb:

code:
require "socket"

PORT = 5535
NAME = ARGV.shift or "Anon"

chat_client = TCPSocket.new("localhost", PORT)

while line = gets do chat_client.puts(line) end

Author:  wtd [ Thu Aug 05, 2004 8:27 pm ]
Post subject: 

I considered putting it here, but it was inspired by the post in Turing Tutorials. Smile


: