带有backgroundWorker的C#TCP客户端

时间:2013-04-26 06:34:45

标签: c# tcp backgroundworker

我有一个用C#编写的TCP客户端,我使用backgroundWorker连接服务器,如下所示:

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

我有一个计时器来检查clientSocket.Connected是真还是假,如果不是,我会再次拨打ConnectToServer()进行另一次连接尝试。

问题是我每次关闭应用程序并重新打开它时,似乎最后一个套接字仍然存在,并且有两个具有相同IP但不同端口连接到服务器的套接字。

即使我有这样的事情:

void bwConnector_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {

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

关于断开连接,我有这样的代码:

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

根据SO的建议在此做出回应。

可悲的是,现实世界的应用程序往往会失败并且往往会出现意想不到的事情。被用户意外关闭可能是最明显的“意想不到的事情”。我会确保,如果没有别的,至少在退出时清理所有东西。

最后,一切都由你决定。