问题从的TcpClient阅读 [英] Problem reading from a TCPClient

查看:191
本文介绍了问题从的TcpClient阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做在C#中一个简单的客户端应用程序,并已达到一个问题。

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.

我得到的问题,看完这个字符串的时候,是我的程序首先读取一个字符串的,然后下一次我读我得到消息的剩余部分。 例如,如果我做什么,我收到的WriteLine,它是这样的: (如果他将1 0 0 0)

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 message. 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 

(编辑:格式化似乎不容许这样做的1一排它自己的,其余的都应该是排在下面,其中包括空间preceding第一0)

( 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)

我已经江郎才尽了如何解决这一问题。这里的方法(我评论了一些东西,我试过): http://pastebin.com/0bXC9J2f

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是基于基于流,而不是消息。其中可以包含以下任一方案:

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

  • 在消息的蝇头纤细的一部分
  • 在一个半消息
  • Excactly一个消息
  • 在一个半消息
  • 两个消息

因此​​,你需要使用某种方法来看看一个完整的消息已经到达。最常见的方法是:

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

  • 添加脚注(例如空行),这表明消息的​​结束
  • 添加包含消息的长度固定长度的头

这篇关于问题从的TcpClient阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆