在C#中,可以使用Socket.ReceiveTimeoutSocket.SendTimeout属性来设置连接超时。

以下是一个示例代码:

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

class Program
{
    static void Main(string[] args)
    {
        // 创建Socket对象
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // 设置连接超时为5秒
        socket.ReceiveTimeout = 5000;
        socket.SendTimeout = 5000;

        try
        {
            // 连接到服务器
            socket.Connect(IPAddress.Parse("127.0.0.1"), 8080);
            Console.WriteLine("连接成功");
        }
        catch (SocketException ex)
        {
            Console.WriteLine("连接超时:" + ex.Message);
        }

        // 关闭Socket连接
        socket.Close();

        Console.ReadLine();
    }
}

在上述代码中,socket.ReceiveTimeoutsocket.SendTimeout属性被设置为5000毫秒(即5秒)。如果连接操作在5秒内没有完成,将会抛出一个SocketException异常。

C#Socket设置连接超时

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

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