现在我正在为Skypatrol TT8750 +的消息开发某种解析器,并且我的线程化TCP服务器正在工作。问题在于,如果同时连接很多设备,这不是一个好方法。我正在使用碘,但我不能让一些代码给我工作。我的目标是首先收到一条33bytes的信息来识别设备,然后开始接收86bytes的车辆信息。用碘处理AVL消息
require 'iodine'
# define the protocol for our service
class TT8750plus
@timeout = 10
def on_open
puts "New Connection Accepted."
# this file is just for testing purposes.
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
po += @expecting
@expecting = 86
@msg.clear
end
if(length > 0)
@msg << (buffer[pos, length])
@expecting = 86 - length
end
puts @msg
end
def on_close
@out_file.close
end
end
# create the service instance
Iodine.listen 12050, TT8750plus
# start the service
Iodine.start
并且在一切消息
New Connection Accepted.
Iodine caught an unprotected exception - NoMethodError: undefined method `+' for nil:NilClass
iodineServer.rb:26:in `on_message'
iodineServer.rb:1:in `on_data'Iodine caught an unprotected exception - NoMethodError: undefined method `+' for nil:NilClass
出现此错误也该实现没有得到我所需要的 这些都是前两行,我从这个实现了消息:
0021000a0800000000000120202020202038363332383630323034333433373020
0021000a08000000000001202020202020383633323836303230343334333730200056000a08100020202020202038363332383630323034333433373020014b0000
这些是线程执行的前两行
0021000a0800000000000120202020202038363332383630323034333433373020
0056000a08100020202020202038363332383630323034333433373020000b00000013090044709bfb8109e400000000001100000000000067eb11090c1512012e970020000000000005000000000005000000000007
0056000a08100020202020202038363332383630323034333433373020010b00000013090044709bfb8109e400000000001200000000000067eb11090c1512042e970020000000000005000000000005000000000008
在线程实现中,第一行似乎是86字节长,而不是第一个消息所期望的33字节....修复异常(请参阅我的答案)应该修复正在处理的其他消息。 – Myst
这是因为我在我的测试文件中忽略了第一行,但它与我在该碘服务器中显示的第一行相同。谢谢@Myst –