“Connection reset by peer” error occured when new tcp socket
The code below aims at making TCP Server and Clients. But when the number of the client threads is too big(for example: 100 threads), then client receives an "Connection reset by peer" error. I can't find out the cause of the error, so I need your help.
Server:
#!/usr/bin/env ruby1.9
# -*- coding: utf-8 -*-
require "socket"
crab = TCPServer.new "127.0.0.1", 8087
while browser = crab.accept
Thread.new browser do | client |
puts client.gets
client.puts "hello"
client.close
end
end
Client:
#!/usr/bin/env ruby1.9
# -*- coding: utf-8 -*-
require "socket"
threads_arr = []
ARGV[0].to_i.times do
t = Thread.new do
client = TCPSocket.new "127开发者_如何学JAVA.0.0.1", 8087
client.puts "hello"
client.gets
client.close
end
threads_arr << t
end
threads_arr.each do | t |
t.join
end
Envrionment:
Mac OS X 10.6.8
ruby 1.8.7p174 / ruby 1.9.2p180
Would this be easier to do in EventMachine? Threading will only scale so far before it starts to cause trouble. EventMachine also handles load better when receiving a large number of connections.
You may need to check that your accept queue is sufficiently large. The default is something like 5 pending connections and if they can't be acknowledged quickly enough you might have them dropped.
Socket connection should be closed on one side - or client only or server only. In your example if server close connection first client receive exception when try close connection.
Delete for example close
call in client:
t = Thread.new do
client = TCPSocket.new "127.0.0.1", 8087
client.puts "hello"
client.gets
end
精彩评论