如何在ruby中运行后台线程?

use*_*457 5 ruby multithreading chat backgroundworker

我是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
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是客户.

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
Run Code Online (Sandbox Code Playgroud)

谢谢

Max*_*Max 9

阅读文档Thread.new(与Thread.start此处相同)

Thread.start(commands)运行该commands方法并将其返回值传递给一个线程(然后什么都不做).它是阻塞因为你在gets调用时没有启动任何线程.你要

Thread.start { commands }
Run Code Online (Sandbox Code Playgroud)

这是一个类似的演示脚本,可以像你期望的那样工作

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
Run Code Online (Sandbox Code Playgroud)