我有一個C#TCP服務器應用程序。我檢測到TCP客戶端與服務器斷開連接時發生斷開連接,但我如何檢測到有線拔出事件?當我拔下以太網電纜時,我無法檢測到斷開連接。聽取以太網電纜拔出TCP服務器應用程序的事件
3
A
回答
0
您可能想要應用「ping」功能,如果發生TCP連接丟失,該功能將失敗。使用此代碼將擴展方法添加到套接字:
using System.Net.Sockets;
namespace Server.Sockets {
public static class SocketExtensions {
public static bool IsConnected(this Socket socket) {
try {
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
} catch(SocketException) {
return false;
}
}
}
}
如果沒有可用的連接,方法將返回false。即使您在Reveice/Send方法上沒有SocketExceptions,它也應該檢查是否存在連接。 請記住,如果您發生了與連接丟失有關的錯誤消息的異常,那麼您不需要再檢查連接。
這個方法是用來當套接字看起來像連接但可能不像你的情況。
用法:
if (!socket.IsConnected()) {
/* socket is disconnected */
}
0
0
我發現這個方法here。它檢查連接的不同狀態併發出斷開信號。但未檢測到拔下的電纜。經過進一步的搜索和反覆試驗,我終於解決了這個問題。
作爲Socket
參數,我在服務器端使用來自接受連接的客戶端套接字,在客戶端使用連接到服務器的客戶端。
public bool IsConnected(Socket socket)
{
try
{
// this checks whether the cable is still connected
// and the partner pc is reachable
Ping p = new Ping();
if (p.Send(this.PartnerName).Status != IPStatus.Success)
{
// you could also raise an event here to inform the user
Debug.WriteLine("Cable disconnected!");
return false;
}
// if the program on the other side went down at this point
// the client or server will know after the failed ping
if (!socket.Connected)
{
return false;
}
// this part would check whether the socket is readable it reliably
// detected if the client or server on the other connection site went offline
// I used this part before I tried the Ping, now it becomes obsolete
// return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}
catch (SocketException) { return false; }
}
相關問題
- 1. TCP服務器斷開/電纜拔出
- 2. 拔出以太網電纜和禁用以太網網絡與操作系統之間的區別
- 3. 串口電纜被拔出
- 4. 在Linux中通知「以太網電纜插入」事件
- 5. Wiznet W5100拔出電纜檢測
- 6. Servicestack服務器發送事件 - 電子郵件應用程序
- 7. 如何獲取插入/拔出的電纜狀態
- 8. 網絡電纜拔出時SQL連接不能快速定時
- 9. 通過單根以太網電纜流多線程
- 10. 用於遊戲的以太網電纜類型
- 11. Rails 5應用程序(動作電纜)作爲Socket.io服務器和客戶端
- 12. 如何通過USB電纜從android應用程序訪問tomcat服務器?
- 13. 以太網使用CAT5e電纜而不使用CAT6
- 14. 如果沒有以太網電纜,則以太網開始塊60秒鐘
- 15. 在拔下USB電纜後重新連接應用程序進行調試
- 16. TCP服務器C++程序
- 17. TCP服務器小程序
- 18. 通過以太網電纜將客戶端PC連接到服務器電腦? (java)
- 19. 橋WiFi進行樹莓派使用以太網電纜
- 20. Qt獲取應用程序狀態沒有事件監聽器
- 21. 在精簡框架中檢測'網絡電纜未拔掉'
- 22. 通過以太網電纜將AndroidThings連接到adb
- 23. 從服務器偵聽事件,Chrome擴展程序
- 24. 關於事件監聽器,小服務程序
- 25. 使用qt的多客戶端/服務器tcp應用程序
- 26. NET中的TCP應用程序服務器的技術
- 27. 服務應用程序太可見
- 28. 以太網服務器大小限制
- 29. Arduino以太網服務器問題
- 30. C#中的TCP服務器Windows 8 XAML應用程序
不,它沒有工作。我可以檢測到我的電纜拔下事件,但我無法檢測到tcp客戶端的拔下事件。 – sanchop22 2012-04-24 14:21:37
請提供downvote的信息? – moka 2013-08-05 15:28:56