判断socket是否是链接状态
/// <summary> /// 当socket.connected为false时,进一步确定下当前连接状态 /// </summary> /// <param name="client"></param> /// <returns></returns> private bool IsSocketConnected(Socket client) { #region remarks /******************************************************************************************** * 当Socket.Conneted为false时, 如果您需要确定连接的当前状态,请进行非阻塞、零字节的 Send 调用。 * 如果该调用成功返回或引发 WAEWOULDBLOCK 错误代码 (10035),则该套接字仍然处于连接状态; * 否则,该套接字不再处于连接状态。 * Depending on http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.connected.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2 ********************************************************************************************/ #endregion #region 过程 // This is how you can determine whether a socket is still connected. bool connectState = true; bool blockingState = client.Blocking; try { byte[] tmp = new byte[1]; client.Blocking = false; client.Send(tmp, 0, 0); //Console.WriteLine("Connected!"); connectState = true; //若Send错误会跳去执行catch体,而不会执行其try体里其之后的代码 } catch (SocketException e) { // 10035 == WSAEWOULDBLOCK if (e.NativeErrorCode.Equals(10035)) { //Console.WriteLine("Still Connected, but the Send would block"); connectState = true; } else { //Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode); connectState = false; } } finally { client.Blocking = blockingState; } //Console.WriteLine("Connected: {0}", client.Connected); return connectState; #endregion }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
2023-05-08 FreeSql.Generator实体类生成器