我发布此答案是为了解释我对安德森的回答所做的评论。大部分代码不是我的。
将if 移出循环
if 语句在循环中时,每次循环运行时都会对其进行评估,从而增加 CPU 指令的数量和每个循环的复杂度。
您可以通过将条件语句移出循环来提高性能,如下所示:
require 'socket'
require 'celluloid/io'
portnumber = 12050
socketServer = TCPServer.open(portnumber)
incomingData = nil
while true
Thread.new(socketServer.accept) do |connection|
puts "Accepting connection from: #{connection.peeraddr[2]}"
# this should probably be changed,
# it ignores the possibility of two connections arriving at the same timestamp.
t = Time.now.strftime("%d-%m-%Y %H%M")
file_name = t + '.txt'
out_file = File.new(file_name, "w+")
begin
if connection
incomingData = conection.recv(33)
if incomingData != nil
incomingData = incomingData.unpack('H*')[0]
out_file.puts(incomingData)
puts "Incoming: #{incomingData}"
end
end
while connection
incomingData = connection.recv(59)
if incomingData != nil
incomingData = incomingData.unpack('H*')[0]
out_file.puts(incomingData)
puts "Incoming: #{incomingData}"
end
end
rescue Exception => e
# Displays Error Message
puts "#{ e } (#{ e.class })"
ensure
connection.close
out_file.close
puts "ensure: Closing"
end
end
end
优化recv方法
我可能应该提到的另一个优化(但不会在这里实现)是recv 方法调用。
这既是一种优化,也是应该解决的错误的可能来源。
recv 是一个系统调用,由于网络消息可能会跨 TCP/IP 数据包组合(或分段),调用recv 可能比处理解决分段和溢出的内部数据缓冲区更昂贵州。
重新考虑每个客户端的线程设计
我还建议避免使用每个客户端的线程设计。
一般来说,对于少数客户来说,这可能并不重要。
但是,随着客户端数量的增加和线程变得越来越繁忙,您可能会发现系统在上下文切换上花费的资源比实际任务要多。
另一个问题可能是每个线程需要分配的堆栈(1Mb 或 2Mb 用于 Ruby 线程,如果我没记错的话)...在最好的情况下,1000 个客户端将需要超过 1 GB 的内存分配仅用于堆栈(我忽略了内核结构数据表和其他资源)。
我会考虑使用 EventMachine 或 Iodine(我是 iodine 的作者,所以我有偏见)。
事件设计可以为您节省很多资源。
例如(未经测试):
require 'iodine'
# define the protocol for our service
class ExampleProtocol
@timeout = 10
def on_open
puts "New Connection Accepted."
# this should probably be changed,
# it ignores the possibility of two connections arriving at the same timestamp.
t = Time.now.strftime("%d-%m-%Y %H%M")
file_name = t + '.txt'
@out_file = File.new(file_name, "w+")
# a rolling buffer for fragmented messages
@expecting = 33
@msg = ""
end
def on_message buffer
length = buffer.length
pos = 0
while length >= @expecting
@msg << (buffer[pos, @expecting])
out_file.puts(msg.unpack('H*')[0])
length -= @expecting
pos += @expecting
@expecting = 59
@msg.clear
end
if(length > 0)
@msg << (buffer[pos, length])
@expecting = 59-length
end
end
def on_close
@out_file.close
end
end
# create the service instance
Iodine.listen 12050, ExampleProtocol
# start the service
Iodine.start