我正在尝试设置一个tcp连接,该连接将从外部用户接收一些xml格式的数据,将其解析为数据表,对数据表执行一些繁重的操作,然后转身,根据更改发送xml答复。
从外观上看,它似乎运行得很好,但随后测试出现了一些重大问题。如果一次输入多个项,有时会返回错误的数据(就像第三个输入发送第四个ins数据应答),并且有可能在非常长的xml输入中没有正确地接收所有数据。
接收端
此代码用于接收传入的传输,将其解析为xml文档,然后将它们发送到适当的部分进行处理。有些全局声明(如_TcpClient__)没有显示初始化,因为我认为它们的数据类型等可能是显而易见的。
private void ReceivePortMessages()
{
int requestCount = 0;
_TcpListener.Start();
Debug.Print(" >> Server Started");
_TcpClient = _TcpListener.AcceptTcpClient();
Debug.Print(" >> Accept connection from client");
while (true)
{
try
{
requestCount = requestCount++;
NetworkStream networkStream = _TcpClient.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)_TcpClient.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
XmlDocument xm = new XmlDocument();
xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
XmlElement root = xm.DocumentElement;
string rootName = root.FirstChild.Name;
// Sends the data to an appropriate parser operation.
RouteInboundXML(rootName, dataFromClient);
}
catch (ArgumentOutOfRangeException ex)
{
Debug.Print("ReceivePortMessages: Remote client disconnected. " + ex.ToString());
_TcpClient.Close();
_TcpListener.Stop();
ReceivePortMessages();
return;
}
catch (Exception ex)
{
Debug.Print("ReceivePortMessages: " + ex.ToString());
_TcpClient.Close();
_TcpListener.Stop();
ReceivePortMessages();
return;
}
}
}正在发送的传输
接收到此数据后,通过一系列操作路由xml文档,包括插入数据库、处理插入数据库的数据,然后通过SQL service broker依赖项将数据提取起来并将其转换为xml应答文档。然后,service的依赖项调用SendReply方法来向用户返回一个答复。该代码可在下面找到:
private void SendReply(string reply)
{
try
{
NetworkStream networkStream = _TcpClient.GetStream();
string serverResponse = reply;
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Debug.Print(" >> " + serverResponse);
}
catch (ArgumentOutOfRangeException ex)
{
Debug.Print("SendReply: Remote client disconnected. " + ex.ToString());
_TcpClient.Close();
_TcpListener.Stop();
ReceivePortMessages();
return;
}
}弄明白这一点对我来说是一个伟大的胜利,因为我在网络编程领域相当缺乏(正如你可能知道的)。我已经在这个项目上工作了近5个月,实际上只剩下这个部分了。任何编码建议,阅读材料,等等,帮助我解决这一点将是令人难以置信的感谢。提前谢谢。
发布于 2015-01-29 16:50:29
您的字节缓冲区是静态的,我将从以下位置切换它:
byte[] bytesFrom = new byte[10025];至:
byte[] bytesFrom = new byte[tcpClient.ReceiveBufferSize];另外,我将切换到Unicode编码,它来自:
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);至:
string dataFromClient = Encoding.UTF8.GetString(bytesFrom);另外,在.Read()之前添加一个读取超时,从10开始,查看是否有任何更改生效:
networkStream.ReadTimeout = 10;https://stackoverflow.com/questions/28218984
复制相似问题