One method I did not discuss in detail in the previous post (1) was “SetSocketOption”.
The “SetSocketOption” method is used to set certain characteristics of a socket. Let us look the following.
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
You can read more about the “SocketOptionLevel” enumeration here - http://msdn.microsoft.com/en-us/library/system.net.sockets.socketoptionlevel.aspx.
According to MSDN “SocketOptionName.ReuseAddress” “Allows the socket to be bound to an address that is already in use.” But what does this mean in practise...
When “Socket.Close” is called on a socket it goes into a “TIME_WAIT” state. We will discuss this in a later post.
Consider a case where the Server shuts down with a fatal exception. There is no guarantee that the socket has been closed gracefully. At this stage the socket will move into a “TIME_WAIT” state and remain in this state until the client is notified. Remember that TCP is a “reliable” communication protocol.
If we restart the Server, it will try to use the same port that it was using before. But this will fail because the socket is in a “TIME_WAIT” state. This is where “ReuseAddress” enumeration comes into play. By enabling address reuse, the Server can bind to the same endpoint it was using prior to the crash.
Resources:
http://meteatamel.wordpress.com/2010/12/01/socket-reuseaddress-property-and-linux/
No comments:
Post a Comment