Connection gpsCn = new Connection(connection);
Thread thread = new Thread(new ThreadStart(gpsCn.WaitForSendData));
thread.Name = connection.RemoteEndPoint.ToString();
thread.Start();
Connection 類別封裝 Socket 並提供 WaitForSendData 方法,解決 ThreadStart 無參數限制。
while (true)
{
byte[] bytes = new byte[1024];
string data = "";
int bytesRec = _connection.Receive(bytes); // 阻塞等待資料
_lastConnectTime = DateTime.Now;
if (bytesRec == 0) { Logger.Log("Close", _connection.RemoteEndPoint.ToString()); break; }
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
// 處理 data ...
}
Receive 同步阻塞,無資料不返回。bytesRec == 0 表示對方關閉連線。
// Listener 靜態成員
static public Hashtable Connections = new Hashtable();
// 建立連線時存入
Connections[connection] = thread; // 或自訂 Key
// Connection 內更新最後活動時間
_lastConnectTime = DateTime.Now;
// WinForm 定期掃描 Hashtable,移除逾時連線