我有一个我在ruby中制作的TCP服务器,服务器似乎工作,我可以看到两个或更多客户端可以连接并由服务器提供服务,但是,它们有时会卡住(因为需要等待通常在" pass_ok"之后的其他客户端断开连接或只是没有响应bit,当只与一个客户端连接时,我不会看到这个问题。
这是我的代码:
def self.main_server
begin
server = TCPServer.open(@port)
rescue Exception => e
CoreLogging.syslog_error("Cant start server: #{e}")
end
@main_pid = Process.pid
# Main Loop
Thread.abort_on_exception = true
while true
Thread.fork(server.accept) do |client|
@client = client
sock_domain, remote_port, remote_hostname, remote_ip = @client.peeraddr # Get some info on the incoming connection
CoreLogging.syslog_error("Got new connection from #{@client.peeraddr[3]} Handeled by Thread: #{Thread.current}") # Log incoming connection
@client.puts "Please enter password: " # Password testing (later will be from a config file or DB)
action = @client.gets(4096).chomp # get client password response 'chomp' is super important
if action == @password
# what to do when password is right
pass_ok
Thread.exit
else
# what to do when password is wrong
pass_fail
Thread.exit
end
end
begin
CoreLogging.syslog_error("Thread Ended (SOFT)")
rescue Exception => e
CoreLogging.syslog_error("Thread was killed (HARD)")
end
end
end
答案 0 :(得分:0)
我会留在这里供将来参考,并希望处于紧密状态的人会发现它很有用。
问题是全局的@client变量,它被覆盖了每个新线程,然后继承到线程内的子类。
使用本地客户端变量(没有' @')让它按预期工作。