我有一个用 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;
}
}
}
感谢帮助。