我是新手,想用Ruby重建一个我以前用C#编写的简单聊天程序。
我使用的是Ruby 2.0.0 MRI(Matz的Ruby实现)。
问题在于我希望在服务器运行时拥有简单的服务器命令I/O。这是从示例中获取的服务器。我添加了使用gets()获取输入的commands方法。我希望这个方法在后台作为线程运行,但该线程正在阻塞其他线程。
require 'socket' # Get sockets from stdlib
server = TCPServer.open(2000) # Socket to listen on port 2000
def commands
x = 1
while x == 1
exitProgram = gets.chomp
if exitProgram == "exit" || exitProgram == "Exit"
x = 2
abort("Exiting the program.")
end
end
end
def main
Thread.start(commands)
Thread.start(server.accept)
loop { # Servers run forever
Thread.start(server.accept) do |client|
client.puts(Time.now.ctime) # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close # Disconnect from the client
end
}
end
main
这是目前的客户端。
require 'socket' # Sockets are in standard library
hostname = 'localhost'
port = 2000
s = TCPSocket.open(hostname, port)
while line = s.gets # Read lines from the socket
puts line.chop # And print with platform line terminator
end
s.close # Close the socket when done
gets.chomp