C winsock “rolling parsing”

…衆ロ難τιáo~ 提交于 2020-01-25 03:21:09

问题


i'm trying to receive data from a server and parse it.

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?

the function that is supposed to be doing this is called msgLoop() and is located in the second pastebin line.


回答1:


To read an \n-terminated string from a socket, you have to either:

  1. read from the socket 1 byte at a time until you encounter a \n byte. 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. If not, then keep reading from the socket in larger blocks and store them into the cache until you encounter a \n byte. 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.




回答2:


There's no built-in "readLine" method for sockets. 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/



来源:https://stackoverflow.com/questions/4825605/c-winsock-rolling-parsing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!