我有一个通过 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;
}