Ruby TCPSocket 不断失去连接
我有一个客户端和服务器。我启动服务器并运行客户端,第一次它工作正常。第二次运行客户端(不重新启动服务器)时,客户端似乎挂起。任何人都可以看到出了什么问题吗?
我有一个客户端:
# 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
和服务器:
# 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")
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")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每个与服务器的连接都需要单独的接受调用才能被接收。发生的情况是,您接受第一个,使用它,然后有效地终止,同时使套接字处于侦听状态。这意味着连接将被打开,但不会被接受,因此它们会按照您的描述挂起。
使用更强大的服务器框架可能会更好。 EventMachine (http://rubyeventmachine.com/) 学习起来有点棘手,但比推出您自己的解决方案。
这里有一个可能会有所帮助的快速修复:
现在,accept 调用被包装在一个循环中,因此可以处理多个连接。
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.
Here's a quick fix that might help:
Now the accept call is wrapped in a loop so more than one connection can be processed.