C# TCP网络流发送和接收

C# TCP网络流发送和接收,c#,networking,tcp,tcplistener,networkstream,C#,Networking,Tcp,Tcplistener,Networkstream,我开发了一个TCP侦听器来接收来自客户机的消息,获取该字符串并将其放入数据库,然后返回一个带有与该字符串相关的数据的响应。第一次尝试tcp网络流发送和回复时,只需要看看这是否会导致任何容易避免的打嗝或返回不正确的数据。如果接收到多条消息,有时我会在网络流上得到一个无法访问的对象。不知道如何纠正这些问题 private void ReceivePortMessages() { try { _TcpListener.Start(); Debug.Pri

我开发了一个TCP侦听器来接收来自客户机的消息,获取该字符串并将其放入数据库,然后返回一个带有与该字符串相关的数据的响应。第一次尝试tcp网络流发送和回复时,只需要看看这是否会导致任何容易避免的打嗝或返回不正确的数据。如果接收到多条消息,有时我会在网络流上得到一个无法访问的对象。不知道如何纠正这些问题

private void ReceivePortMessages()
{
    try
    {
        _TcpListener.Start();
        Debug.Print(" >> Server Started");
        _TcpClient = _TcpListener.AcceptTcpClient();
        Debug.Print(" >> Accept connection from client");
        Boolean isProcessing = true;
        using (NetworkStream networkStream = _TcpClient.GetStream())
        {
            while (isProcessing)
            {
                try
                {
                    int receivingBufferSize = (int)_TcpClient.ReceiveBufferSize;
                    byte[] bytesFrom = new byte[receivingBufferSize];
                    networkStream.Read(bytesFrom, 0, receivingBufferSize);
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
                    if (dataFromClient != string.Empty)
                    {
                        XmlDocument xm = new XmlDocument();
                        xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
                        XmlElement root = xm.DocumentElement;
                        string rootName = root.FirstChild.Name;
                        // Data is sent to be processed and sent back.
                        RouteInboundXML(rootName, dataFromClient, sw);
                    }
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    Debug.Print("ReceivePortMessages: Remote client disconnected. " + ex.ToString());
                    _TcpClient.Close();
                    _TcpListener.Stop();
                    ErrorLog.Write("MotionIndustriesXmlProcessing", ex.ToString(), "ReceivePortMessages()");
                    return;
                }
                catch (Exception ex)
                {
                    Debug.Print("ReceivePortMessages: " + ex.ToString());
                    _TcpClient.Close();
                    _TcpListener.Stop();
                    ErrorLog.Write("MotionIndustriesXmlProcessing", ex.ToString(), "ReceivePortMessages()");
                    return;
                }
            }
            Debug.Print(" >> exit");
            isProcessing = false;
        }
    }
    catch (Exception ex)
    {
        Debug.Print("ReceivePortMessages: " + ex.ToString());
        ErrorLog.Write("MotionIndustriesXmlProcessing", ex.ToString(), "ReceivePortMessages()");
    }
    ReceivePortMessages();
}

private void RouteInboundXML(string requestType, string requestXML, Stopwatch sw)
{
    //
    // A bunch of other operations happen and then they call the SendReply() method.
    //
    SendReply();
}

private void SendReply(string reply)
{
    try
    {
        using (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();
        return;
    }
}

你的实际问题是什么?你在寻找测试代码的可能性吗?@TobiasKnauss我想我关心的是,如果十条消息同时命中会发生什么?系统如何知道首先回复哪一个?它排队了吗?我想我只是不完全理解它为什么会起作用,尽管它或多或少已经起作用了。但同时没有。操作系统的TCP堆栈按照接收顺序将消息转发到输入缓冲区。将在输入缓冲区中连接,因此您需要找到如何再次将它们分开的方法,例如定义固定的消息布局。进一步:你会得到什么错误?您是否尝试过跳过并调试?为了调试TCP通信,我建议使用HW集团公司的一个小程序hercules。调用Read而不保留它返回的值永远都不是正确的做法。我不知道你还有什么错误,但这是我看到的第一个主要错误。在第二次查看之后,您似乎还假设您在一次读取中读取了整个XML文档,这也是一个源代码errors@ScottChamberlain如果是重大错误,建议的修复方法是什么?我在寻找如何让它变得更好,而不仅仅是出了什么问题。上面的代码是我能从众多在线页面中找到的最好的代码。帮帮我,好吗?