Amai
Amai

Reputation: 51

Is initializing a new socket in every method a good thing?

So I'm trying to tackle sockets programming in C# .NET, but there are no good articles/guides about it from what I've seen and found (even the official MSDN site has outdated code in there). I'm trying to follow this link here, but since it's quite out-dated, I'm unsure if the code included in there is considered good practice. And so, there's this code:

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

    listener.BeginAccept(new AsyncCallback(acceptCallback), listener);
}

And then there is this code:

public void acceptCallback(IAsyncResult ar) {
    Socket listener = (Socket) ar.AsyncState;
    Socket handler = listener.EndAccept(ar);
}

Why does the acceptCallback initialize a new socket? Why do all the methods initialize a socket of their own? Wouldn't it be better to justhave one, class-wide private socket like this

private Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);? And why does it first create a listener socket and then a handler socket? What's the point to that? Also, what happens to the listener passed as an argument in the BeginAccept method? From the looks of it, it just goes and dies in a black hole.

And lastly, I'd be very grateful for any and all links to tutorials/articles which could help me understand socket programming.

Upvotes: 1

Views: 1526

Answers (1)

Richard
Richard

Reputation: 109015

Why does the acceptCallback initialize a new socket?

This is how the BSD derived socket APIs work (and reflects how the TCP/IP network stack works).

You create a first socket whose sole job is to wait for incoming connections: via the Listen (or variant) method and then establish the connection via Accept method (or variant).

Which returns another Socket instance that will be used for communicate with one client1 socket.

The initial listening socket continues to be available for new incoming connections.

This reflects the model of a server with many clients connecting to it.

One can think of Socket being overloaded with two functions: 1. listing for and accepting connections, 2. representing an established connection.

Stack Overflow does not generally do recommendations (they tend to become out of date too quickly): I learnt this when Sun systems ran Sun OS writing in C at the end of the 80s so I'm in no position to recommend anything anyway :-).


1 Once a connection is established operations between client and server are – at the socket level – symmetric, but it is useful to think about server & client roles when thinking about establishing connections.

Upvotes: 1

Related Questions