【发布时间】:2012-10-22 14:17:18
【问题描述】:
我有一个通过 TCP/IP 连接到另一个应用程序的类发送请求(以 XML 的形式)并接收响应(也以 XML 的形式)。
它确实有效,但我有以下担忧:
1) 它只适用于任意System.Threading.Thread.Sleep(5000);如果我把它拿出来,它会直接跳到带有部分数据的类的末尾。我需要它等到它到达流的末尾或超时。
2) 不是很优雅
下面列出了整个班级,欢迎提出任何建议。
public XDocument RetrieveData()
{
// Initialize Connection Details
TcpClient Connection = new TcpClient();
Connection.ReceiveTimeout = Timeout;
MemoryStream bufferStream = new MemoryStream();
// Compose Request
String Request = "";
Byte[] Data = ASCIIEncoding.ASCII.GetBytes(Request);
// Connect to PG
IAsyncResult ConnectionResult = Connection.BeginConnect(IPAddress, IPPort, null, null);
while (!Connection.Connected)
{
System.Threading.Thread.Sleep(1000);
}
Connection.EndConnect(ConnectionResult);
NetworkStream ConnectionStream = Connection.GetStream();
// Send the request
ConnectionStream.Write(Data, 0, Data.Length);
ConnectionStream.Flush();
// TODO. Tidy this up - Wait to ensure the entire message is recieved.
System.Threading.Thread.Sleep(5000);
// Read the response
StringBuilder Message = new StringBuilder();
byte[] ReadBuffer = new byte[1024];
if (ConnectionStream.CanRead)
{
try
{
byte[] myReadBuffer = new byte[1024];
int BytesRead = 0;
do
{
BytesRead = PGConnectionStream.Read(myReadBuffer, 0, myReadBuffer.Length);
Message.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, BytesRead));
}
while (PGConnectionStream.DataAvailable);
}
catch
{
}
}
XDocument doc = XDocument.Parse(Message.ToString());
return doc;
}
【问题讨论】:
-
如果您只是在同一个线程中等待建立连接,我什至无法理解您为什么要使用 BeginConnect...
-
而不是等待 5 秒循环,直到您看到“消息结束”或 5 秒(或超时值)结束。一种机制是搜索文档的结束标签,当您看到它时尝试解析...如果通过退出等待...如果不继续等待。