|
First, what is the port reuse:
In the realization of winsock, the server can be bundled multiple bundled in determining who use multiple bonding time, in accordance with a principle is the most clear who will be the designated packet submitted to the Who, and is not the purview of the points . This is called multiple bundled port reused.
Second, how do we achieve Socket port reuse:
In fact, we will have to use very simple port complex, we can use SetSocketOption function can be set up on the Socket options. MSDN is explained:
Options for the current Socket Socket behaviour. For a Boolean data type option can be designated non-zero value of the options open to designate the zero value of the option can be disabled. For integer data type with the option to designate an appropriate value. Socket options in accordance with the agreement to support groups.
We look at how this function is used:
Public void SetSocketOption (
SocketOptionLevel optionLevel,
SocketOptionName optionName,
Int optionValue
)
Parameters
OptionLevel
SocketOptionLevel value of one.
OptionName
SocketOptionName value of one.
OptionValue
The value of the options.
These parameters we can look at MSDN. Here I do not speak of.
Here we optionLevel parameters-SocketOptionLevel.Socket; optionName parameters-SocketOptionName.ReuseAddress; optionValue Senate-a non-zero value, I Chuan is True, if banned, it would Chuan False.
Such as:
Socket2.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Below we look at the specific code:
We first established the first Socket:
Socket socket1;
IPEndPoint localEP = new IPEndPoint (IPAddress.Any, 20000);
Socket1 = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket1.Bind (localEP);
Then a second Socket:
Socket socket2
IPEndPoint localEP = new IPEndPoint (IPAddress.Any, 20000);
Socket2 = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket2.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
/ / Please note this one. True ReuseAddress options will be set to allow the socket to bind already in use in the address.
Socket2.Bind (localEP);
This will be bundled Socket1 and Socket2 in the same port on the.
|