From: James Edward Gray II Date: 2005-09-05T08:05:20+09:00 Subject: Re: [SOLUTION] MUD Client (#45) A very basic quick solution I thew together. This only works on Unix (requires stty). If you want to play with scripting it, run once, then edit ~/.mud_client_rc: #!/usr/local/bin/ruby -w require "thread" require "socket" require "io/wait" def show_prompt puts "\r\n" print "#{$prompt} #{$output_buffer}" $stdout.flush end $input_buffer = Queue.new $output_buffer = String.new $end_session = false $prompt = ">" $reader = lambda { |line| $input_buffer << line.strip } $writer = lambda do |buffer| $server.puts "#{buffer}\r\n" buffer.replace("") end $server = TCPSocket.new(ARGV.shift || "localhost", ARGV.shift || 61676) config = File.join(ENV["HOME"], ".mud_client_rc") if File.exists? config eval(File.read(config)) else File.open(config, "w") { |file| file.puts(<<'END_CONFIG') } # Place any code you would would like to execute inside the Ruby MUD client at # start-up, in this file. This file is expected to be valid Ruby syntax. # Set $prompt to whatever you like as long as it supports to_s(). # You can set $end_session = true to exit the program at any time. # $reader and $writer hold lambdas that are passes the line read from the # server and the line read from the user, respectively. # # The default $reader is: # lambda { |line| $input_buffer << line.strip } # # The default $writer is: # lambda do |buffer| # $server.puts "#{buffer}\r\n" # buffer.replace("") # end END_CONFIG end Thread.new($server) do |socket| while line = socket.gets $reader[line] end puts "Connection closed." exit end $terminal_state = `stty -g` system "stty raw -echo" show_prompt until $end_session if $stdin.ready? character = $stdin.getc case character when ?\C-c break when ?\r, ?\n $writer[$output_buffer] show_prompt else $output_buffer << character print character.chr $stdout.flush end end break if $end_session unless $input_buffer.empty? puts "\r\n" puts "#{$input_buffer.shift}\r\n" until $input_buffer.empty? show_prompt end end puts "\r\n" $server.close END { system "stty #{$terminal_state}" } __EMD__ While I was making this, I wanted a stupid simple server to play with, so I rolled one up: #!/usr/local/bin/ruby -w require "gserver" class ChattyServer < GServer def initialize( port = 61676, *args ) super(port, *args) end def serve( io ) messages = Array[ "Hello there.", "Welcome to ChattyServer.", "Isn't this a lovely conversation we're having?", "Is this \e[31mred\e[0m?" ] loop do io.puts messages[rand(messages.size)] sleep 5 end end end server = ChattyServer.new server.start server.join __EMD__ James Edward Gray II