0
C#TCP客戶端我都寫在C#中的TCP客戶端,我使用BackgroundWorker的連接的服務器,這樣的事情:與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
是真的還是假的,如果爲false,我將再次撥打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;
}
}
}
感謝您的幫助。
你在哪裏關閉連接? – Abhinav 2013-04-26 06:50:00
我在問題中增加了一些代碼,謝謝 – AkariKamigishi 2013-04-26 07:33:06
如果我理解正確,你打開一個連接 - >準備套接字來接受數據 - >開始接收數據 - >關閉連接。這一切都很好,並保持一切順序。問題似乎是從該計時器中產生的,該計時器一旦關閉就立即打開連接。所以就在你的應用程序關於退出之前,Timer會打開一個永遠不會關閉的連接。 – Abhinav 2013-04-26 07:37:59