简体   繁体   English

C winsock“滚动解析”

[英]C winsock “rolling parsing”

i'm trying to receive data from a server and parse it. 我正在尝试从服务器接收数据并解析它。

http://pastebin.com/1kjXnXwq http://pastebin.com/XpGSgRBh http://pastebin.com/1kjXnXwq http://pastebin.com/XpGSgRBh

everything works as is, but i want to parse the data instead of just grabbing blocks of it and printing it out. 一切都按原样工作,但我想解析数据,而不是只是抓取它的块并打印出来。 so is there any way to grab data from the winsock until \\n then stop and pass it off to another function to be parsed and once that function returns continue reading from the last point until another \\n shows up and repeate the process until there is nothing left to receive? 所以有没有办法从winsock中获取数据,直到\\ n然后停止并将其传递给另一个要解析的函数,一旦该函数返回继续从最后一个点读取,直到另一个\\ n显示并重复该过程,直到有什么都没收到?

the function that is supposed to be doing this is called msgLoop() and is located in the second pastebin line. 应该执行此操作的函数称为msgLoop(),位于第二个pastebin行中。

To read an \\n -terminated string from a socket, you have to either: 要从套接字读取\\n终止字符串,您必须:

  1. read from the socket 1 byte at a time until you encounter a \\n byte. 每次从套接字读取1个字节,直到遇到\\n字节。 Any unread bytes are left in the socket until you read them later. 任何未读的字节都会保留在套​​接字中,直到您稍后再读它们为止。 This is not very efficient, but it works. 这不是很有效,但它有效。

  2. create a data cache. 创建数据缓存。 When you need a new string, first check the cache to see if there is already a \\n byte present in it. 当您需要一个新字符串时,首先检查缓存以查看其中是否存在\\n字节。 If not, then keep reading from the socket in larger blocks and store them into the cache until you encounter a \\n byte. 如果没有,则继续从较大的块中读取套接字并将它们存储到缓存中,直到遇到\\n字节。 Then process the contents of the cache up to the first \\n byte, remove the bytes you processed, and move any remaining bytes to the front of the cache for later reads. 然后处理缓存的内容直到第一个\\n字节,删除您处理的字节,并将任何剩余的字节移动到缓存的前面以便以后读取。

There's no built-in "readLine" method for sockets. 套接字没有内置的“readLine”方法。 So, you'll need to implement it yourself, but it's not too tricky. 所以,你需要自己实现它,但它并不太棘手。 I found this example by Googling, you may be able to improve on it: 我通过谷歌搜索找到了这个例子,你可以改进它:

http://johnnie.jerrata.com/winsocktutorial/ http://johnnie.jerrata.com/winsocktutorial/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM