views:

157

answers:

1

I've got a client app which has to connect to a server and register for waiting, that is, it wants to be notified when the server is done with some processing. Ideally, I want to keep this client as simple as possible, but the question is, how to "register for waiting". I could keep the socket open and do a blocking read, and as soon as the server is done, it'll send some data to the client and I'm done; unfortunately this blocks one port on the server for quite some time.

What alternatives are there? I could pick a random port on the client side, and listen for a connection there, but this requires me to pick a free random port -- and I'm not sure how to do this best in C#? I thought about checking the local port used while sending to the server, and re-using this; I wonder if there is some recommended way to solve this. Polling from the client is out of question, as the time between finish and notification shouldn't be too long.

+1  A: 

Pass 0 as the port number to the IPEndPoint constructor:

Socket.Bind Remarks on MSDN:

If you do not care which local port is used, you can create an IPEndPoint using 0 for the port number. In this case, the service provider will assign an available port number between 1024 and 5000.

If you use the above approach, you can discover what local network address and port number has been assigned by calling the LocalEndPoint. If you are using a connection-oriented protocol, LocalEndPoint will not return the locally assigned network address until after you have made a call to the Connect or EndConnect method. If you are using a connectionless protocol, you will not have access to this information until you have completed a send or receive.

Mehrdad Afshari