从 ByteBuffer 中提取-字符串 - 我很困惑
我已经解决这个问题几个小时了,但没有让它按照我希望的方式工作。
我正在创建一个从 telnet 客户端读取数据的服务器。服务器使用 java.nio (ServerSocketChannel) 并读取 ByteBuffer。每次 read() 之后,我调用一个方法,该方法应该从 ByteBuffer 中提取所有行(用“\r\n”分隔),并以某种方式保留剩余的字节(如果有),以便下一个 read() 放置它们处于正确的位置。
示例:
read() 读取 6 个字节,ByteBuffer 现在包含“Hi\r\nHo”。我想要做的是提取所有完全收到的字符串,在本例中为“Hi\r\n”。我希望将“Ho”留在 ByteBuffer 中,进行移位以使“H”位于位置 0,这样当我下次调用 read() 并收到“w are you?\r\n”时,它会被放置在 ByteBuffer 中的正确位置。
我创建了一个小型测试程序,但我似乎无法让它正确执行: http://pastebin.com/eun1nV2N
尝试不同的测试字符串(“HI”、“HI\r\n”、“HI\r\nHEY\r”等),您会看到它何时失败。 (我使用eclipse调试工具来检查变量)
I've been sitting with this problem for some hours now without getting it to work the way I want it to work.
I'm creating a server which reads data from a telnet client. The server uses java.nio (ServerSocketChannel) and reads into a ByteBuffer. After each read() I'm calling a method which is suppose to extract all lines (seperated by "\r\n") from the ByteBuffer and leave the (if any) remaining bytes in a way so the next read() puts them in the correct position.
Example:
read() reads 6 bytes, the ByteBuffer now contains "Hi\r\nHo". What I want to do is to extract all completely recieved strings, in this example "Hi\r\n". I want to "Ho" to be left in the ByteBuffer, shifted so that the "H" is at position 0, so that when I call read() next time and recieve "w are you?\r\n", it will be put at the correct place in the ByteBuffer.
I created a small test program but I can't seem to get it to do it correct: http://pastebin.com/eun1nV2N
Try different test strings ("HI", "HI\r\n", "HI\r\nHEY\r", etc) and you'll see when it fails. (I used the eclipse debug tool to inspect variables)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将 ByteBuffer 包装为一个 InputStream 和一个 BufferedReader,然后您应该能够使用 readline 来逐行获取行。
Try wrapping the ByteBuffer an InputStream and a BufferedReader, then you should be able to use readline to get the lines one by one.