在TCP協議中,對於斷開的一方其本地用來通訊的端口(系統分配的)仍然會被保留一段時間。所以客戶端斷開后立即再連就是失敗。解決的途徑就是換一個本地的通訊端口,由於不能手動指定一個新端口那就只能重新創建TcpClient實例。
在重新創建TcpClient之前要釋放掉原TcpClient所占有的資源。
C#代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Threading; namespace OnLineVideo.Util { public class SocketClient { private TcpClient client; private bool isConnection=false; private string hostip;//TCP服務器 private int port;//端口 //檢查網絡狀態線程 Thread checkStateThread; public SocketClient(string hostip, int port) { this.hostip = hostip; this.port = port; client = new TcpClient(); try { client.Connect(hostip, port); } catch { IsConnection = false; } checkStateThread = new Thread(new ThreadStart(checkState)); checkStateThread.IsBackground = true; checkStateThread.Start(); } /// <summary> /// 獲取或者設置網絡連接狀態 /// </summary> public bool IsConnection { get { return isConnection;} set { isConnection = value; } } private void checkState() { while (true) { Thread.Sleep(1000); if (client.Connected== false) { try { client.Close(); client = new TcpClient(); client.Connect(hostip, port); IsConnection = true; } catch { IsConnection = false; } } } } public void SendCommand(string strMessage) { try { byte[] bytesArray = Encoding.ASCII.GetBytes(strMessage+"\n"); NetworkStream networkStream = client.GetStream(); networkStream.Write(bytesArray,0,bytesArray.Length); }catch { IsConnection = false; } } public void Close() { client.Close(); } } }