简体   繁体   中英

C# TCP client with backgroundWorker

I have a TCP client written in C#, and I use backgroundWorker to connect the server, something like this:

void ConnectToServer() {
    try {
        bwConnector = new BackgroundWorker();
        bwConnector.DoWork += new DoWorkEventHandler(bwConnector_DoWork);
        bwConnector.RunWorkerCompleted = new RunWorkerCompletedEventHandler(bwConnector_RunWorkerCompleted);
        bwConnector.RunWorkerAsync();
        e.Result = true;
    } catch {
        e.Result = false;
    }
}

void bwConnector_DoWork(object sender, DoWorkEventArgs e) {

    clientSocket = new Socket(xxxxxx);
    clientSocket.Connect(xxxx);

    this.networkStream = new NetworkStream(this.clientSocket);
    this.bwReceiver = new BackgroundWorker();
    this.bwReceiver.DoWork += new DoWorkEventHandler(StartReceive);
    ........
}

And I have a timer to check clientSocket.Connected is true or false, if false, I will call ConnectToServer() again for another connection attempt.

The problem is everytime I closed the application and reopen it, it seems that the last socket still remain there and have 2 sockets with the same IP but different ports connecting to the server.

Even I have something like this:

void bwConnector_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {

    ((BackgroundWorker)sender).Dipose();
    if (!((bool)e.Result)) {
        Debug.Log("failed");
    } else {
        Debug.Log("success");
    }
}

For disconnection, I have such codes:

System.Net.NetworkInformation.NetworkChange.NetworkAvailablilityChanged += new System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler(NetworkAvailabilityChanged);
private void NetworkChange_NetworkAvailabilityChanged(object sender , System.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
    {
        if ( !e.IsAvailable )
        {
            this.OnNetworkDead(new EventArgs());
            this.OnDisconnectedFromServer(new EventArgs());
        }
        else
            this.OnNetworkAlived(new EventArgs());
    }
...............
public event DisconnectedEventHandler DisconnectedFromServer;
protected virtual void OnDisconnectedFromServer(EventArgs e)
{
    if ( DisconnectedFromServer != null )
    {
        DisconnectedFromServer(this , e);
    }
}
...........
void StartReceive(xxxxxxxxx) {
    while (this.clientSocket.Connected) {
        .........
    }
    this.Disconnect();
}

bool Disconnect() {
    if (this.clientSocket != null && this.clientSocket.Connected) {
        try {
            this.clientSocket.Shutdown(SocketShutdown.Both);
            this.clientSocket.Close();
            return true;
        } catch {
            return false;
        }
    }
}

Thanks for help.

Responding here as suggested by SO.

Sadly, real world applications tend to fail and often time unexpected things happen. Being accidently closed by a user might be the most obvious "unexpected thing". I would have made sure that, if nothing else, at least everything is cleaned up on exit.

In the end, its all upto you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM