Knight King Knight King - 2 months ago 11
C# Question

Socket program crashes computer

Here is the code.If you try to run,the program will crash your computer

IPEndPoint ip = new IPEndPoint(IPAddress.Any, 10000);
Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sk.Bind(ip);
sk.Listen(100);
while (true) {
sk.BeginAccept(new AsyncCallback(OnReveive), sk);
}

private static void OnReveive(IAsyncResult ar) {
Socket sock = (Socket) ar.AsyncState;
Socket cl = sock.EndAccept(ar);
Console.WriteLine("New Connection from" + cl.RemoteEndPoint.ToString());
}


I want to ask why does it crash my computer

Answer
  while (true) {
    sk.BeginAccept(new AsyncCallback(OnReveive), sk);
  }

BeginAccept is an async method that instantly returns so your code rapidly fills up the memory pool with new AsyncCallback(OnReveive) callbacks. Call it only once, don't put it in a while.

Or call the blocking method Accept().