开发者

Reading a line from a socket

I am writing some code in which i need to get a line from a socket whenever the line ends in a newline or carriage return. The line shoould be stored in a buffer.

 n = recv(sock, &ch, 1, 0);
  if (n > 0)
  {
   if (ch == '\r')
   {
       // do stuff
   }
     //
  }
   //
开发者_StackOverflow

I am using code like this inside a while but it is not working any clues How can i do this.

Edited: I want one line to be read from the socket and returned to be parsed. This should hap[pen for each line read.


This is similar to the recent question entitled "getline over a socket".

The answer is that you should not do this. What would happen if the client did not send the next line? Your program would hang.

From your code snippet, you do not appear to be checking the error codes. These would indicate why your code is "nor working" and would indicate where to start looking for the problem.


1) Maybe you have carriage return / linefeed?

2) Maybe ch is overflowing?

3) Maybe your stream is binary and \r is valid for non-EOL?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜