在 CRLF 分隔符上拆分字符串但最后可能有不完整的消息(没有 CRLF)的最佳方法是什么?
buf1 = "msg1\r\nmsg2\nmsg3\r\nmsg_no_CRLF"
buf2 = "msg1\r\nmsg2\nmsg3\r\nmsg4\r\n"
a = buf1.scan(/.*\r?\n|.*/)
>>> ["msg1\r\n", "msg2\n", "msg3\r\n", "msg_no_CRLF", ""]
a = buf2.scan(/.*\r?\n|.*/)
>>> ["msg1\r\n", "msg2\n", "msg3\r\n", "msg4\r\n", ""]
我尝试为数组的最后一项获取空字符串或不完整的消息。
>>> ["msg1\r\n", "msg2\n", "msg3\r\n", "msg_no_CRLF"]
>>> buf1 = a.last # "" or "msg_no_CRLF"
编辑:我有这个方法:
def read
msgs = []
@buffer << @socket.read_nonblock(1024)
while @buffer.slice!(/(.*)\r?\n/)
msgs << $1
end
msgs
end
那行得通,但我尝试在两行中通过扫描或拆分来做同样的事情。
该方法必须返回完整消息的数组(每个 CRLF 之前的所有部分)。
@buffer = "msg1\r\nmsg2\r\n"
# Ok, return ["msg1", "msg2"] and @buffer is set to ""
@buffer = "msg1\r\nmsg2"
# incomplete msg2, return ["msg1"] and @buffer is set to "msg2" for the next read.
对不起我的英语,很难正确解释。