TCP网络流发送和接收

时间:2015-02-27 16:40:25

标签: c# networking tcp tcplistener networkstream

我开发了一个TCP侦听器来接收来自客户端计算机的消息,获取该字符串并将其放入数据库,然后发回一个响应,其中包含与该字符串相关的一些数据。首次尝试tcp网络流发送和回复,只需看看是否会导致任何容易避免的"打嗝"或返回不正确的数据。如果收到多条消息,有时我的网络流上会收到Cannot access disposed object。不确定如何纠正这些问题。

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;
    }
}

0 个答案:

没有答案