我是ruby的新手,并认为重建一个我在C#中创建的简单聊天程序是个好主意.
我正在使用Ruby 2.0.0 MRI(Matz的Ruby实现).
问题是我希望在服务器运行时为简单的服务器命令提供I/O. 这是从示例中获取的服务器.我添加了使用gets()获取输入的命令方法.我希望这个方法在后台运行作为一个线程,但该线程阻止了另一个线程.
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 # …Run Code Online (Sandbox Code Playgroud)