简体   繁体   English

Ruby TCPSocket不断丢失连接

[英]Ruby TCPSocket keeps losing connection

I have a client and server. 我有一个客户端和服务器。 I start up the server, and run the client, and the first time it works fine. 我启动服务器,并运行客户端,并且第一次运行良好。 The second time I run the client(without restarting the server), the client appears to hang. 第二次运行客户端(不重新启动服务器)时,客户端似乎挂起。 Can anyone see what is wrong? 谁能看到错在哪里?

I have a client: 我有一个客户:


# Code example originated from p069dtclient.rb at http://rubylearning.com/satishtalim/ruby_socket_programming.html
    require 'socket'
    x = 0;

    streamSock = TCPSocket.new( 'localhost', 20000 )
    while x < 10
      streamSock.send( "Hello #{x}",0 )
      str = streamSock.recv( 100 )
      puts "#{x} " + str
      x=x+1
    end
    streamSock.close

And server: 和服务器:


    # p068dtserver.rb
    require "socket"
    dts = TCPServer.new('localhost', 20000)
    s = dts.accept
    print(s, " is accepted\n")
    loopCount = 0;
    loop do
      Thread.start(s) do
      loopCount = loopCount + 1
        lineRcvd = s.recv(1024)
        if ( !lineRcvd.empty? )
          puts("#{loopCount} Received: #{lineRcvd}")
          s.write(Time.now)
        end
      end
    end
    s.close
    print(s, " is gone\n")

Each connection to the server requires a separate accept call in order to be received. 与服务器的每个连接都需要一个单独的接受调用才能被接收。 What's happening is that you're accepting the first, working with it, and then effectively terminating while leaving the socket in a listening state. 发生的情况是,您首先接受,使用它,然后在使套接字保持监听状态的同时有效终止。 This means connections will be opened, but not accepted, so they hang as you describe. 这意味着将打开连接,但不接受连接,因此它们会按照您的描述挂起。

You might be better off using a more robust server framework. 使用更强大的服务器框架可能会更好。 EventMachine ( http://rubyeventmachine.com/ ) is a little tricky to learn, but is far more powerful than a roll your own solution. EventMachine( http://rubyeventmachine.com/ )学习起来有些棘手,但它远比滚动您自己的解决方案强大。

Here's a quick fix that might help: 这是一个可能有帮助的快速修复:

require "socket"
dts = TCPServer.new('localhost', 20000)
while (s = dts.accept)
  print(s, " is accepted\n")
  loopCount = 0;
  loop do
    Thread.start(s) do
    loopCount = loopCount + 1
      lineRcvd = s.recv(1024)
      if ( !lineRcvd.empty? )
        puts("#{loopCount} Received: #{lineRcvd}")
        s.write(Time.now)
      end
    end
  end
  s.close
  print(s, " is gone\n")
end

Now the accept call is wrapped in a loop so more than one connection can be processed. 现在,accept调用被包装在一个循环中,因此可以处理多个连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM