C#TCP客户端在断开连接和重新连接后无法发送消息的问题

时间:2018-03-27 01:05:07

标签: c# .net tcp

我遇到的问题是,在客户端连接并重新连接后,我的TCP侦听器没有收到任何数据。我是TCP / IP的新手,所以我确信它只是一个我不理解的概念或逻辑错误。日志中没有任何错误或明显的问题(对我而言)。

客户代码

/// <summary>
/// Class for sending data over TCP
/// </summary>
public class TcpMessageSender : MessageSender
{
    /// <summary>
    /// Udp Client that sends messages
    /// </summary>
    public TcpClient TcpClient { get; private set; }

    /// <summary>
    /// Constructor which initializes the client
    /// </summary>
    public TcpMessageSender(string ipAddress, int port)
    {
        ConnectToAddress(ipAddress, port);
        TcpClient = new TcpClient();
    }

    /// <summary>
    /// Constructor which initializes the client
    /// </summary>
    public TcpMessageSender(IPAddress ipAddress, int port)
    {
        ConnectToAddress(ipAddress, port);
        TcpClient = new TcpClient();
    }

    /// <summary>
    /// Default constructor
    /// </summary>
    public TcpMessageSender()
    {
        TcpClient = new TcpClient();
    }

    /// <summary>
    /// Sends data over a network stream using the client
    /// </summary>
    /// <param name="data"></param>
    public override void SendMessage(byte[] data)
    {
        NetworkStream nwStream = TcpClient.GetStream();

        if(nwStream != null)
        {
            nwStream.Write(data, 0, data.Length);
        }
    }

    /// <summary>
    /// Connects the Tcp client to the end point
    /// </summary>
    public void Connect()
    {
        TcpClient.Connect(IPEndPoint);
    }

    /// <summary>
    /// Closes the connection
    /// </summary>
    public override void CloseConnection()
    {
        TcpClient.Close();
    }
}

服务器代码

public class TcpMessageReceiver : MessageReceiver
{
    /// <summary>
    /// Listener for getting values
    /// </summary>
    public TcpListener TcpListener { get; private set; }

    /// <summary>
    /// Call back for receiving data
    /// </summary>
    public Action<string> OnReceivedData;

    /// <summary>
    /// Message callback from the thread
    /// </summary>
    public string MessageData { get; private set; }

    /// <summary>
    /// Listen thread reference
    /// </summary>
    private Thread m_ListenThread;

    /// <summary>
    /// Flag to tell the thread to stop
    /// </summary>
    private bool m_KillThread_Flag = false;

    /// <summary>
    /// Constructor for setting up a new listener
    /// </summary>
    /// <param name="address">IP Address</param>
    /// <param name="port">Port</param>
    public TcpMessageReceiver(IPAddress address, int port)
    {
        ConnectToAddress(address, port);
        TcpListener = new TcpListener(IPEndPoint);
    }

    /// <summary>
    /// Constructor for setting up a new listener
    /// </summary>
    /// <param name="address">IP Address</param>
    /// <param name="port">Port</param>
    public TcpMessageReceiver(string address, int port)
    {
        ConnectToAddress(address, port);
        TcpListener = new TcpListener(IPEndPoint);
    }

    /// <summary>
    /// Starts the listening thread
    /// </summary>
    public void StartListening()
    {
        m_KillThread_Flag = false;
        ThreadStart childref = new ThreadStart(ListenThread);
        m_ListenThread = new Thread(childref);
        m_ListenThread.Start();
    }

    /// <summary>
    /// Kills the listen thread and stops the TCP Listener
    /// </summary>
    public void StopListening()
    {
        m_KillThread_Flag = true;
        TcpListener.Stop();
    }

    /// <summary>
    /// Thread for listening for incomign data
    /// </summary>
    private void ListenThread()
    {
        TcpListener.Start();
        TcpClient client = TcpListener.AcceptTcpClient();

        while (!m_KillThread_Flag)
        {
            try
            {
                if (client.GetStream() != null)
                {
                    NetworkStream nwStream = client.GetStream();

                    if (nwStream.DataAvailable)
                    {
                        byte[] buffer = new byte[client.ReceiveBufferSize];

                        //---read incoming stream---
                        int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

                        //---convert the data received into a string---
                        string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);

                        if (OnReceivedData != null)
                        {
                            OnReceivedData.Invoke(dataReceived);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageData = e.Message;
            }
        }
    }

    /// <summary>
    /// Tells the listener to stop
    /// </summary>
    public override void CloseConnection()
    {
        StopListening();
    }
}

出于兼容性原因,我需要尝试坚持使用.NET 3.5。如果有必要,还有一些升级空间。如果有任何关于代码的超级明显的话我肯定会感激它被指出给我。

但只是澄清一下。我遇到的问题是,如果我启动服务器,然后启动客户端。他们互动很好。如果我断开客户端然后重新连接它,服务器将不会从该客户端接收数据。我不确定这是否只是试图在同一台机器上运行服务器和客户端的问题。但任何帮助肯定会受到赞赏!

0 个答案:

没有答案