One, what is the port multiplexing:
Because in the implementation of Winsock, the binding of the server can be multiple-bound, in determining the use of multiple bindings who, according to a principle whose designation is most clearly handed to who, and does not have permission points. This multiple binding is called Port multiplexing.
Second, how we implement the socket port multiplexing:
In fact, we want to implement port multiplexing is very simple, we just use the SetSocketOption function to set the socket option. This is explained by MSDN:
The socket option determines the behavior of the current Socket. For an option with a Boolean data type, specifying a value other than 0 can enable the option, and specifying a value of 0 can disable the option. For an option with an integer data type, specify the appropriate value. The Socket options are grouped according to the protocol support level.
Let's take a look at how this function is used:
public void SetSocketOption (
SocketOptionLevel optionLevel,
SocketOptionName optionName,
int optionValue
)
Parameters
Optionlevel
One of the socketoptionlevel values.
Optionname
One of the socketoptionname values.
OptionValue
The value of the option.
The above parameters you can go to see MSDN. I don't have much to say here.
Here we are optionlevel Parameter pass socketoptionlevel.socket;optionname parameter pass Socketoptionname.reuseaddress;optionvalue a non 0 value, I pass true, if you want to disable it, pass false.
Such as:
Socket2. SetSocketOption (Socketoptionlevel.socket, socketoptionname.reuseaddress, true);
Specifically, let's look at the following code:
We first set up 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 create 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);
//请注意这一句。ReuseAddress选项设置为True将允许将套接字绑定到已在使用中的地址。
socket2.Bind(localEP);
So Socket1 and Socket2 are bound to the same port.
Example routines code I uploaded to my resources, you can go to Http://www.cnblogs.com/Files/wzd24/28135640620.rar to download.