0

我有以下将客户端传递给 HandleStationClients 的客户端侦听器。HandleStationClients 的构造函数在其他线程中启动一个带有连接的任务以进行侦听。

下面的代码使用异步函数在主线程上运行。当客户端连接时,下面的等待部分将继续并将客户端传递给新创建的 HandleStationClients 并挂钩事件。通常在连接事件之后,循环将重新开始并在等待时等待新的连接。问题是此代码为每个连接循环两次。因此,客户端连接并创建 HandleStationClients,事件将被挂钩,while 循环再次开始,然后继续运行相同的进程,再次创建新的 HandleStationClients 和事件挂钩。

处理完客户端后,等待者不会等待而是继续第二次。事件被触发两次。我不知道怎么了。有人有线索吗?

while (true)
{
    counter += 1;

    // Wait for new connection then do rest
    stationsClientSocket = await stationsServerSocket.AcceptTcpClientAsync();

    stationClients.Add(stationsClientSocket, 0);
    Debug.WriteLine("Client toegevoegd " + counter);

    HandleStationClients stationClient = new HandleStationClients(stationsClientSocket);

    stationClient.ConnectionEstabilished += stationClient_ConnectionEstabilished;
    stationClient.ConnectionClosed += stationClient_ConnectionClosed;
    stationClient.NewDataReceived += stationClient_NewDataReceived;
}

HandleClient 看起来像

class HandleStationClients
{
    public HandleStationClients(TcpClient client)
    {
        Task.Factory.StartNew(() => { ProcessConnection(client); });
    }

    #region Event definitions
    public delegate void NewDataReceivedEventHandler(string newData);
    public event NewDataReceivedEventHandler NewDataReceived;

    public delegate void ConnectionClosedEventHandler();
    public event ConnectionClosedEventHandler ConnectionClosed;

    public delegate void ConnectionEstabilishedEventHandler(IPEndPoint endpoint);
    public event ConnectionEstabilishedEventHandler ConnectionEstabilished;
    #endregion

    public async void ProcessConnection(TcpClient stationsClientSocket)
    {
        byte[] message = new byte[1024];
        int bytesRead;

        NetworkStream networkStream = stationsClientSocket.GetStream();

        if (this.ConnectionEstabilished != null)
        {
            this.ConnectionEstabilished((IPEndPoint)stationsClientSocket.Client.RemoteEndPoint);
        }

        while ((true))
        {
            bytesRead = 0;

            try
            {
                bytesRead = await networkStream.ReadAsync(message, 0, 1024);
            }
            catch (Exception ex)
            {
                // some error hapens here catch it                    
                Debug.WriteLine(ex.Message);
                break;
            }

            if (bytesRead == 0)
            {
                //the client has disconnected from the server
                break;
            }

            ASCIIEncoding encoder = new ASCIIEncoding();

            if (this.NewDataReceived != null)
            {
                byte[] buffer = null;

                string incomingMessage = encoder.GetString(message, 0, bytesRead);

                this.NewDataReceived(incomingMessage);
            }
        }
        stationsClientSocket.Close();
        // Fire the disconnect Event
        this.ConnectionClosed();
    }
}
4

2 回答 2

1

在构造函数中启动任务是个坏主意。这意味着在您注册事件处理程序时您的任务正在运行。很有可能有时您不会在需要触发之前注册事件。

您应该做的是等待启动任务,直到事件处理程序全部注册。您将需要创建一个Start方法来处理启动任务,并在注册事件后让代码调用它。

更新的类:

class HandleStationClients
{
    // Added a field to store the value until the Start method
    TcpClient _client;

    public HandleStationClients(TcpClient client)
    {
        this._client = client;
        // Moved the line from here...
    }

    public void Start()
    {
        // ...to here.
        Task.Factory.StartNew(() => { ProcessConnection(_client); });
    }

    #region Event definitions
    // ...
    #endregion

    public async void ProcessConnection(TcpClient stationsClientSocket)
    {
        byte[] message = new byte[1024];
        int bytesRead;

        NetworkStream networkStream = stationsClientSocket.GetStream();

        if (this.ConnectionEstabilished != null)
        {
            this.ConnectionEstabilished((IPEndPoint)stationsClientSocket.Client.RemoteEndPoint);
        }

        while ((true))
        {
            bytesRead = 0;

            try
            {
                bytesRead = await networkStream.ReadAsync(message, 0, 1024);
            }
            catch (Exception ex)
            {
                // some error hapens here catch it                    
                Debug.WriteLine(ex.Message);
                break;
            }

            if (bytesRead == 0)
            {
                //the client has disconnected from the server
                break;
            }

            ASCIIEncoding encoder = new ASCIIEncoding();

            if (this.NewDataReceived != null)
            {
                byte[] buffer = null;

                string incomingMessage = encoder.GetString(message, 0, bytesRead);

                this.NewDataReceived(incomingMessage);
            }
        }
        stationsClientSocket.Close();
        // Fire the disconnect Event
        // I added a line to check that ConnectionClosed isn't null
        if (this.ConnectionClosed != null)
        {
            this.ConnectionClosed();
        }
    }
}

然后你需要改变调用代码如下。

while (true)
{
    counter += 1;

    // Wait for new connection then do rest
    stationsClientSocket = await stationsServerSocket.AcceptTcpClientAsync();

    stationClients.Add(stationsClientSocket, 0);
    Debug.WriteLine("Client toegevoegd " + counter);

    HandleStationClients stationClient = new HandleStationClients(stationsClientSocket);

    stationClient.ConnectionEstabilished += stationClient_ConnectionEstabilished;
    stationClient.ConnectionClosed += stationClient_ConnectionClosed;
    stationClient.NewDataReceived += stationClient_NewDataReceived;
    // Call Start manually
    stationClient.Start();
}
于 2012-05-13T00:08:00.923 回答
0

我将 Task start 从构造函数移到 Start 方法。问题解决了。

于 2012-05-12T23:49:02.493 回答