C# 实时监测 TCP 客户端连接状态:IP 地址和端口号
要实时判断 TCP 客户端 IP 地址和端口号是否连接成功并保持连接,可以使用以下代码:
using System;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
IPAddress ipAddress = IPAddress.Parse('127.0.0.1'); // 服务器IP地址
int port = 8888; // 服务器端口号
while (true)
{
try
{
TcpClient client = new TcpClient();
client.Connect(ipAddress, port); // 连接服务器
Console.WriteLine('连接成功,IP地址:{0},端口号:{1}', client.Client.RemoteEndPoint.ToString(), ((IPEndPoint)client.Client.RemoteEndPoint).Port);
// 保持连接
while (client.Connected)
{
// 发送和接收数据
// ...
// 延时一段时间
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine('连接已关闭');
}
catch (Exception ex)
{
Console.WriteLine('连接失败:{0}', ex.Message);
}
// 延时一段时间
System.Threading.Thread.Sleep(1000);
}
}
}
这段代码将不断尝试连接服务器,并实时判断连接是否成功,并保持连接。如果连接断开,将自动重新连接。
原文地址: https://www.cveoy.top/t/topic/onEo 著作权归作者所有。请勿转载和采集!