C # Server - Socket Does Not Connect and the Insufficient Memory Exception


I am trying to implement a simple TCP server and I basically copied the example on MSDN sans a couple of lines and tried to make it work. I have an external client trying to connect already. This is my code:

IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
 IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList[0], 4001);

 Socket listener = new Socket(localEP.Address.AddressFamily,
     SocketType.Stream, ProtocolType.Tcp);


    while (true)

         listener.BeginAccept(new AsyncCallback(AcceptCnxCallback), listener);
 catch (Exception e)
   //Log here

This is my callback:

private void AcceptCnxCallback(IAsyncResult iar)

    MensajeRecibido msj = new MensajeRecibido();

    Socket server = (Socket)iar.AsyncState;
    msj.workSocket = server.EndAccept(iar);


And this is the information of one of the incoming packages:

TCP:[SynReTransmit #1727889]Flags=......S., SrcPort=57411, DstPort=4001, PayloadLen=0, Seq=673438964, Ack=0, Win=5840 ( Negotiating scale factor 0x4 ) = 5840

Source: Destination:

I basically have two issues:

  1. If I use the while loop I get an OutOfMemoryException

  2. I never do manage to connect to the client

Any tips on either of the two problems? Thank you in advance!

Your problem is, that you use asynchronous calls all the time. There is no wait mechanism or similar, so generally you are just creating new asynchronous callbacks in an infinite loop.

For a basic TCP I would recommend to use the simple approach and use the synchronous methods. Accept() is blocking, so the program flow will stop until there is an ingoing connection.

while (true)
    Socket s = listener.Accept();

    buffer = new byte[BUFFER_SIZE];
    //Do something


Noe that this is just a basic example. If you want to keep your connection you might consider a new Thread for each accepted Socket, that continoues with receiving and sending data.