1

This is my listening function and connection function

Socket Listen

public void Listen(){
IPEndPoint ep = new IPEndPoint(IPAddress.Any, PortNumber);
Listen.Bind(ep);
Listen.Listen(10);
Listen.BeginAccept(new AsyncCallback(NewConnection), null);}

public void NewConnection(IAsyncResult asyn)
{
    Socket Accepted = Listen.EndAccept(asyn);
    Listen.BeginAccept(new AsyncCallback(NewConnection), null);
    SomeFunction(Accepted);
}

the code works fine and there is no problem - I traced the code to see how to work with different clients and I understand the flow. However, I don't understand how can 1 socket serve different clients. Does it time multiplex between the clients over the socket?

I read on MSDN that Accepted in my code can be only used for the established connection and can't be used any further - that part I don't understand. What actually happens when the client tries to connect to the server socket? Does EndAccept return a totally different socket with different port to establish the connection and keep listening with the same socket to accept more requests at the same time?

1 Answer 1

1

What you've said is basically correct, based on my understanding. The Accepted socket is not the same as Listen. After you EndAccept, you can kick off another BeginAccept async call with your listen socket, and you can use the newly created socket to communicate with your remote peer.

To verify, you can check the local port of the listen socket and the connected socket; they should be different.

Sign up to request clarification or add additional context in comments.

2 Comments

I debugged 2 different clients at the same time trying to connect to the same server, they both got connected to a different port, but the server handle them both with the same port, i don't understand how
Each socket (server and client) has a local endpoint and a remote endpoint. These endpoints may not match in the way that you might expect, I believe. So, if the client connects to the server on port 4000, the client's remote endpoint port is 4000, but the server's local endpoint port may not be 4000. Is this what you mean? (Additionally, the client's local endpoint port is somewhat arbitrarily assigned -- someone who understands better than I can explain, but it's most likely not going to be 4000)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.