开发者

Problem reading from a TCPClient

开发者 https://www.devze.com 2023-03-09 02:04 出处:网络
I\'m making a simple client application in C#, and have reached a problem. The server application sends a string in the format of \"<number> <param> <param>\" etc. In other words, t

I'm making a simple client application in C#, and have reached a problem.

The server application sends a string in the format of "<number> <param> <param>" etc. In other words, the first symbol is an integer, and the rest are whatever, all are separated by one space each.

The problem I get, when reading this string, is that my program first reads a string with the , and then the next time I read I get the rest of the messag开发者_开发问答e. For example, if I were to do a writeline on what I receive, it would look like this: (if he sends "1 0 0 0")

1
 0 0 0 

(EDIT: The formatting doesn't seem to permit this. The 1 is on a row of its own, the rest are supposed to be on the row below, including the space preceding the first 0)

I've run out of ideas how to fix this. Here's the method (I commented out some stuff I tried): http://pastebin.com/0bXC9J2f

EDIT (again): I forgot, it seems to work just fine when I'm in debug and just go through everything step by step, so I can't find any source of the problem that way.


TCP is stream based and not message based. One Read can contain any of the following alternatives:

  • A teeny weeny part of message
  • A half message
  • Excactly one message
  • One and a half message
  • Two messages

Thus you need to use some kind of method to see if a complete message have arrived. The most common methods are:

  • Add a footer (for instance an empty line) which indicates end of message
  • Add a fixed length header containing the length of the message


If your protocol is straight TCP, then you cannot send messages, strings or anything else except octet, (byte) streams. Does your 'string' have a null at the end? If so, you need to append received data until the null arrives, then you have your message.

If this is your problem, then you should code your protocol so that it works no matter how many read calls are made on the socket, eg. if a null-terminated string of [99 data bytes+#0] is sent by the server, your protocol should be able to assemble the correct string if 100 bytes are returned in one call, 1 byte is received in 100 calls, or anything in between.

Rgds, Martin

0

精彩评论

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