如何在ruby中运行后台线程?
我是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 # 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
谢谢
阅读Thread.new
的文档(这里与Thread.start
相同)
Thread.start(commands)
运行commands
方法并将其返回值传递给线程(然后不执行任何操作)。 它是阻塞的,因为在调用gets
时你没有启动任何线程。 你要
Thread.start { commands }
这是一个类似的演示脚本,可以像你期望的那样工作
def commands while gets.strip !~ /^exit$/i puts "Invalid command" end abort "Exiting the program" end Thread.start { commands } loop do puts "Type exit:" sleep 2 end