可以使用 TcpClient 类的 Connected 属性来判断 TCP 客户端是否连接成功。如果 Connected 属性为 true,则表示连接成功。而要获取客户端的 IP 地址和端口号,则可以使用 TcpClient 类的 Client 属性的 RemoteEndPoint 属性。以下是示例代码:

using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        TcpClient client = new TcpClient();
        client.Connect('localhost', 8888); // 连接服务器

        // 判断是否连接成功
        if (client.Connected)
        {
            Console.WriteLine('连接成功');

            // 获取客户端IP地址和端口号
            IPEndPoint remoteEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;
            Console.WriteLine($'客户端IP地址:{remoteEndPoint.Address}');
            Console.WriteLine($'客户端端口号:{remoteEndPoint.Port}');
        }
        else
        {
            Console.WriteLine('连接失败');
        }

        Console.ReadLine();
    }
}
C# 实时判断 TCP 客户端连接状态及获取 IP 地址和端口号

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

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