问题描述
我是红宝石的新手,并且认为重建一个用C#编写的简单聊天程序将是一个好主意.
I am new to ruby and thought it would be a great idea to rebuild a simple chat program I made in C#.
我正在使用Ruby 2.0.0 MRI(Matz的Ruby实现).
I am using Ruby 2.0.0 MRI (Matz’s Ruby Implementation).
问题是服务器运行时我想为简单的服务器命令提供I/O.这是从样本中获取的服务器.我添加了使用gets()获取输入的命令方法.我希望此方法在后台作为线程运行,但是该线程阻塞了另一个线程.
The problem is I want to have I/O for simple server commands while the server is running.This is the server that was taken from the sample. I added the commands method that uses gets() to get input. I want this method to run as a thread in the background, but the thread is blocking the other thread.
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
到目前为止,这是客户.
This is the client so far.
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)
runs the commands
method and passes its return value to a thread (which then does nothing). It's blocking because you aren't starting any threads when gets
is called. You want
Thread.start { commands }
这是一个类似的演示脚本,其工作原理与您期望的一样
Here's a similar demo script that works just like you would expect
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
这篇关于如何在Ruby中运行后台线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!