C# socket超时释放端口

2024-11-09 10:29:31
推荐回答(1个)
回答(1):

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

class Program
{
    static void Main(string[] args)
    {
        TcpListener tl = new TcpListener(IPAddress.Any, 8080);
        EventWaitHandle ev = new EventWaitHandle(false, EventResetMode.ManualReset);
        tl.Start();
        var ar = tl.BeginAcceptTcpClient(new AsyncCallback(x => ev.Set()), null);
        if (!ev.WaitOne(TimeSpan.FromSeconds(10)))
            Console.WriteLine("10秒没人理");//10秒没人连接
        else {
            TcpClient tc = tl.EndAcceptTcpClient(ar);
            Console.WriteLine("连接来自"+tc.Client.RemoteEndPoint.ToString());
        }
        return;
    }
}


用异步即可解决