方法一,使用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; //是否使用操作系統(tǒng)shell啟動
p.StartInfo.RedirectStandardInput = true;//接受來自調(diào)用程序的輸入信息
p.StartInfo.RedirectStandardOutput = true;//由調(diào)用程序獲取輸出信息
p.StartInfo.RedirectStandardError = true;//重定向標準錯誤輸出
p.StartInfo.CreateNoWindow = true;//不顯示程序窗口
p.Start();
//向cmd窗口發(fā)送輸入信息 + "&exit"
p.StandardInput.WriteLine(command + "&exit");
p.StandardInput.AutoFlush = true;
//p.StandardInput.WriteLine("exit");
//獲取cmd窗口的輸出信息
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine(output);
p.WaitForExit();
p.Close();
return output;
}
//判斷執(zhí)行結(jié)果是否包含服務(wù)端連接即可
string results = Execute("netstat -n");
if (results.Contains("172.168.52.222:8999"))
{
Console.WriteLine("---results true ---");
}
else
{
Console.WriteLine("---results false ---");
}
方法二,使用客戶端程序再向服務(wù)端臨時創(chuàng)建一個連接,用連接結(jié)果判斷連接情況,記得關(guān)閉臨時創(chuàng)建的連接
方法三,使用DotNetty框架,再ChannelHandlerAdapter接口的ExceptionCaught方法和HandlerRemoved方法監(jiān)聽實時的連接情況
public class TcpServerHandler : ChannelHandlerAdapter
{
/// <summary>
/// 捕獲 異常,并輸出到控制臺后斷開鏈接,提示:客戶端意外斷開鏈接,也會觸發(fā)
/// </summary>
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
Log.WriteLog($"客戶端{context}下線.");
context.CloseAsync();
}
/// <summary>
/// 客戶端下線斷線時
/// </summary>
public override void HandlerRemoved(IChannelHandlerContext context)
{
Log.WriteLog($"客戶端{context}下線.");
base.HandlerRemoved(context);
}
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。