使用EOT,SOH,STX和其他字符读取套接字

时间:2012-08-17 06:25:42

标签: ruby regex sockets celluloid

我正在使用Celluloid IO从套接字读取。传入消息具有以下语法

sometextsometextsometext

其中

SOH = Hex 1
FS  = Hex 1C
STX = Hex 2
ETX = Hex 3
EOT = Hex 4

我的阅读代码是这样的 -

message = ""
begin
  data = socket.readpartial(4096)
  message << data
end until message =~ /not sure what goes here/

我正在寻找一种可靠的方法从插座读取直到EOT。一旦阅读了该消息,我将重新编写相关章节。

有关在套接字读取流和正则表达式中检测上述十六进制字符的一些指导将非常有用。指导?

1 个答案:

答案 0 :(得分:0)

这对我来说非常感谢

def parse(message)
  if message =~ /\001(.*)\01C(.*)\002(.*)\003\004/
    return ($1,$2,$3)
  end
end

def read_until_eot(socket)
  eot_found = false
  message = ''
  begin
    data = socket.read()
    eot_found = !!data['\004']
    message << data
  end until eot_found
  message.chomp!
end

def handle_connection(socket)
  # read from socket until EOT
  message = read_until_eot(socket) # <-- need help with
  if (origin,target,payload) = parse(message) #message can be parsed
    #   process message
    output_message = process(payload)
  end
  # write to socket
  socket.write output_message
  # close socket
  socket.close
end