TCP服务器未接收所有正在发送的数据

时间:2015-05-18 18:35:58

标签: c# xml tcp server tcpserver

尝试设置TCP服务器以从流中获取数据。似乎工作正常,但仅在流小时才有效。一旦我开始发送大量数据,这将失败,只返回一部分字符。有人可以帮我从这里出去吗?为什么我只收到我发送的部分数据?

服务器的流程应该是,接收所有数据,存储到数据库(RouteInboundXml())并开始侦听更多的传入数据。

private void ReceivePortMessages()
{
    string debug = string.Empty;
    try
    {
        Debug.Print(" >> Starting Server");
        IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
        _TcpListener = new TcpListener(ipAddress, TcpPort); ;
        Debug.Print(string.Format("{0}:{1}", ipAddress.ToString(), TcpPort.ToString()));
        _TcpListener.Start();

        Stopwatch sw = new Stopwatch();
        do
        {
            try
            {
                _TcpClient = _TcpListener.AcceptTcpClient();
                Debug.Print(" >> Accept connection from client");
                NetworkStream networkStream = _TcpClient.GetStream();
                int receivingBufferSize = (int)_TcpClient.ReceiveBufferSize;
                byte[] bytesFrom = new byte[receivingBufferSize];
                int Read = 0;
                string dataFromClient = string.Empty;
                if (!sw.IsRunning)
                {
                    sw.Start();
                }
                Read = networkStream.Read(bytesFrom, 0, receivingBufferSize);
                dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
                if (dataFromClient != string.Empty)
                {
                    XmlDocument xm = new XmlDocument();
                    debug = dataFromClient;
                    xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
                    XmlElement root = xm.DocumentElement;
                    string rootName = root.FirstChild.Name;
                    RouteInboundXML(rootName, dataFromClient, sw);
                    sw.Restart();
                }
            }
            catch (Exception ex)
            {
                Debug.Print("ReceivePortMessages: " + ex.ToString());
                _TcpClient.Close();
                _TcpListener.Stop();
                ErrorLog.Write("XmlProcessing", ex.ToString() + "\r\n" + "DataFromClient: " + debug, "ReceivePortMessages()");
                return;
            }
        } while (true);
    }
    catch (Exception ex)
    {
        Debug.Print("ReceivePortMessages: " + ex.ToString());
        ErrorLog.Write("XmlProcessing", ex.ToString(), "ReceivePortMessages()");
    }
}

2 个答案:

答案 0 :(得分:1)

每次调用Stream.Read时,您似乎都希望收到整个XML文档,并且完全 XML文档。这是一个非常非常危险的假设。

流是一个数据流 - 虽然它会被分段为数据包以进行传输,但您不应该期望接收与ReadWrite次呼叫相同数量的数据。 {1}}来电。

每个连接的单个文档的详细信息

如果每个流只有一个文档,您可以大量简化代码使其正常工作。只需使用接受流的XmlDocument.Load重载这一事实:

using (var tcpClient = tcpListener.AcceptTcpClient())
{
    XmlDocument doc = new XmlDocument();
    using (var stream = tcpClient.GetStream())
    {
        doc.Load(stream);
    }
    // Use doc here
}

(如果可以的话,我个人开始使用LINQ to XML,但那是另一回事。)

多个文件的详细信息

如果你想在一个TCP流上多个消息,你应该实现某种&#34; chunking&#34;协议。这样做的一个好方法是将每条消息分成一个&#34;标题&#34;和&#34;身体&#34;标题可以简单到&#34;正文中的字节数&#34;,所以你知道要阅读多少。 (或者,您可以为标头设计协议以包含其他元数据。)

读取标题后,您将从流中读取正文,直到您读取了标题中指示的字节数,或者到达流的末尾(这通常表示错误)。这可能需要多次Read次呼叫。 然后您处于适当的位置,可以将数据解析为XML文档 - 理想情况下,首先不要强制使用自己的二进制文本或文本解码,因为并非所有XML都是ASCII ...

可以设计你的协议,你只需要在消息之间有一个分隔符 - 但这通常要难以实现,因为它混合了#34;阅读数据&#34;和#34;了解数据&#34;。如果你可以使用上面描述的长度前缀方案,那就更简单了。

答案 1 :(得分:0)

以下是我过去使用的一些代码。 适合我。

using (TcpClient client = new TcpClient(ip, port))
{
    var stm = client.GetStream();
    stm.Write(data, 0, data.Length); //Write some data to the stream

    byte[] resp = new byte[1024];
    var memStream = new MemoryStream();
    var bytes = 0;
    client.Client.ReceiveTimeout = 200;

    do
    {
        try
        {
            bytes = stm.Read(resp, 0, resp.Length);
            memStream.Write(resp, 0, bytes);
        }
        catch (IOException ex)
        {
            // if the ReceiveTimeout is reached an IOException will be raised...
            // with an InnerException of type SocketException and ErrorCode 10060
            var socketExept = ex.InnerException as SocketException;
            if (socketExept == null || socketExept.ErrorCode != 10060)
            // if it's not the "expected" exception, let's not hide the error
            throw ex;
            // if it is the receive timeout, then reading ended
            bytes = 0;
        }
    } while (bytes > 0);

    return memStream.ToArray();
}
相关问题