0

我有一个用 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()再次调用以进行另一次连接尝试。

问题是每次我关闭应用程序并重新打开它时,似乎最后一个套接字仍然存在并且有 2 个具有相同 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;
        }
    }
}

感谢帮助。

4

1 回答 1

1

按照 SO 的建议在这里回复。

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

最后,一切都取决于你。

于 2013-04-26T07:57:06.027 回答