 |
|
|
Ruby |
|
Autor: uwe
07.07.2007 13:30 704
|
|
Simpler Chat
|
Server
#!/usr/bin/env ruby
require "socket"
server = TCPServer.new(ARGV[0] || "localhost", 1337)
stream = server.accept
begin
input = Thread.new do
loop {
s = stream.gets.chomp
if s =~ /^MSG (.+?)$/
puts $1
elsif s == "CLOSE"
exit 0
end
}
end
loop {
s = STDIN.gets.chomp
if s == "/CLOSE"
exit 0
else
stream.puts "MSG #{s}"
end
}
ensure
puts "Connection closed."
stream.puts "CLOSE" rescue ()
stream.close
server.close
end
Client
#!/usr/bin/env ruby
require "socket"
if ARGV[0].nil?
STDERR.puts "First Argument must be the hostname."
exit 1
else
hostname = ARGV[0]
end
stream = TCPSocket.new(hostname, 1337)
begin
input = Thread.new do
loop {
s = stream.gets.chomp
if s =~ /^MSG (.+?)$/
puts $1
elsif s == "CLOSE"
exit 0
end
}
end
loop {
s = STDIN.gets.chomp
if s == "/CLOSE"
exit 0
else
stream.puts "MSG #{s}"
end
}
ensure
puts "Connection closed."
stream.puts "CLOSE" rescue ()
stream.close
end
lokal