方法一,使用cmd netstat -n查看当前端口运行情况
public string Execute(string command)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine(command + "&exit");
p.StandardInput.AutoFlush = true;
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine(output);
p.WaitForExit();
p.Close();
return output;
}
string results = Execute("netstat -n");
if (results.Contains("172.168.52.222:8999"))
{
Console.WriteLine("---results true ---");
}
else
{
Console.WriteLine("---results false ---");
}
方法二,使用客户端程序再向服务端临时创建一个连接,用连接结果判断连接情况,记得关闭临时创建的连接
方法三,使用DotNetty框架,再ChannelHandlerAdapter接口的ExceptionCaught方法和HandlerRemoved方法监听实时的连接情况
public class TcpServerHandler : ChannelHandlerAdapter
{
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
Log.WriteLog($"客户端{context}下线.");
context.CloseAsync();
}
public override void HandlerRemoved(IChannelHandlerContext context)
{
Log.WriteLog($"客户端{context}下线.");
base.HandlerRemoved(context);
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性