Closing listening socket also closes accepted sockets (?)


Lenard Gunda


I have the following problem when I am working with sockets in C#. I do not
remember running into the same problem some while ago, when working with
sockets from C++ (using native code, not managed).

I create a server socket, and then listen on it. I then accept a new
connection from that server socket. If I now close the server socket, it
also closes the accepted connection as well, automatically. This feels

In C++ closing the listening socket has no effect on the accepted socket. In
fact I recall seeing some examples, which did just like this.

However, in C#, there seems to be some "mysterious" connection between the

I read the documentation in MSDN Library, and tried searching for this
behaviour. I even looked at the System.Net.Sockets namespace with Reflector,
but did not come across anything usefull. Does anyone know why C# (.NET)
behaves like this, and how it could be made to behave the way classic
winsock behaves?

I would like to close the server socket after the client has connected,
because I do not want to listen any longer for new connections, just
communicate with that single client.

Thanks for any help

Lenard Gunda


as the server normally listening network connections:
//preapring network
TcpListener tcpListener = tcpListener.AcceptSocket();
//got connection here
//as soon as the server program jumps out of the above line
//the server is NOT accepting any new connetions

this is the same 'sematic' as ya wish it to be, isnt it?

Lenard Gunda


I am not sure this is what I want. I do not use the TcpListener class, I
prefer more direct control over my sockets and use only the Socket class

I know that if I do not call accept again, I will never receive a
connection, but I would like to close the listening socket. But as soon as I
call Close() on the server socket, it also closes all related sockets, ones
that were opened through that particular server socket. And I do not want
this to happen.

And as I said, this is not the usual behaviour I have seen from sockets when
working with them in C++.

-Lenard Gunda

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question