要实时判断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);
        }
    }
}

这段代码将不断尝试连接服务器,并实时判断连接是否成功,并保持连接。如果连接断开,将自动重新连接

C#实时判断TCP客户端IP地址和端口号是否连接成功经常连接关闭连接关闭

原文地址: http://www.cveoy.top/t/topic/fH0F 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录