1. What is port multiplexing:
In the implementation of WinSock, the server can be bound multiple times. When determining who is using the multiple bindings, according to one principle, the person who specifies the person who submits the package is the clearest and has no permission. Such multiple bindings are called Port multiplexing.
2. How can we achieve socket port multiplexing:
In fact, it is very easy to implement port multiplexing. We only need to use the setsocketoption function to set socket options. Msdn explains this as follows:
The socket option determines the behavior of the current socket. For Specifies a non-zero value to enable this option, and specifies a zero value to disable this option. Specify an appropriate value for an integer data type. The socket options are grouped by protocol support.
Let's see how this function is used:
Public Void Setsocketoption (
Socketoptionlevel optionlevel,
Socketoptionname optionname,
Int Optionvalue
)
Parameters
Optionlevel
One of the values of socketoptionlevel.
Optionname
One of the values of socketoptionname.
Optionvalue
The value of this option.
For more information about the above parameters, see msdn. I will not talk about it here.
Here, we use the optionlevel parameter to set socketoptionlevel. Socket; The optionname parameter to set socketoptionname. reuseaddress; The optionvalue parameter to a non-zero value. If this parameter is set to true, false is used.
For example:
Socket2.setsocketoption (socketoptionlevel. socket, socketoptionname. reuseaddress, True );
Let's take a look at the followingCode:
First, establish the first socket:
Socket socket1;
Ipendpoint localep = New Ipendpoint (IPaddress. Any, 20000 );
Socket1 = New Socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Socket1.bind (localep );
Create the 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 sentence. Setting the reuseaddress option to true allows you to bind a socket to an existing address.
Socket2.bind (localep );
In this way, socket1 and socket2 are bound to the same port.
RoutineSource codeYou can upload files to my resources at http://files.cnblogs.com/wzd24/28135640620.rarto download files.