C#套接字程序自动关闭

时间:2016-04-19 08:12:50

标签: c# sockets c#-4.0

当我使用这个程序来插入一系列IP地址时,它总是在没有任何消息的情况下自行关闭一段时间。该计划刚刚结束。我该如何解决这个问题? (这是一个控制台项目)

public static void Main(string[] args)
{
    Task[] tasks = new Task[200];
    for (int i = 0; i < 200; i++)
    {
        tasks[i] = Task.Factory.StartNew(() => RunningThread());
    }
    Task.WaitAll(tasks);
    Console.WriteLine("finish...");
    Console.ReadKey();
    //.....
}

public bool SocketIP(string ip, int port)
{
    AutoResetEvent arEvent = new AutoResetEvent(false);
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    if (socket != null)
    {
        socket.Bind(new IPEndPoint(IPAddress.Any, 0));
        socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), CallBack, new ArrayList() { socket, arEvent});
        arEvent.WaitOne(WaitTime);
        if (Rv)
            socket.Shutdown(SocketShutdown.Both);
        socket.Close();
        socket = null;
    }
    return Rv;
}


void CallBack(IAsyncResult ar)
{
    ArrayList list = (ArrayList)ar.AsyncState;
    Socket socket = (Socket)list[0];

    AutoResetEvent arevent = (AutoResetEvent)list[1];

    if (ar.IsCompleted && socket.Connected)
        Rv = true;
    arevent.Set();
}

1 个答案:

答案 0 :(得分:0)

代码看起来应该停在Console.ReadKey()。也许在程序中未处理崩溃。尝试在Exception ex上调试一个完整的主函数en debug。 我的意思是这样的:

public static void Main(string[] args)
{
try{
    Task[] tasks = new Task[200];
    for (int i = 0; i < 200; i++)
    {
        tasks[i] = Task.Factory.StartNew(() => RunningThread());
    }
    Task.WaitAll(tasks);
    Console.WriteLine("finish...");
    Console.ReadKey();
    //.....
}
catch(Exception ex)
{
 Console.WriteLine(ex.Message); <<<--(break point here)
}
}