This example describes the Select model usage of the I/O model in C + +. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
void Main ()
{
Cinitsock Initsock;
USHORT nport = 9999; Port listening on
Socket Slisten =:: Socket (af_inet, sock_stream, ipproto_tcp);
if (Slisten = = Invalid_socket)
{
printf ("Socket error ...");
Return
}
sockaddr_in servaddr = {0};
servaddr.sin_family = af_inet;
Servaddr.sin_port =:: Htons (Nport);
Servaddr.sin_addr. S_un. S_ADDR = Inaddr_any;
if (Socket_error =:: Bind (Slisten, (sockaddr*) &servaddr, sizeof (SERVADDR))
{
int nerror =:: GetLastError ();
printf ("Connect error ...");
Return
}
:: Listen (Slisten, 5);
Select model Processing Process
1. Initialize socket collection, add listening socket to this collection
Fd_set Fdsocket;
Fd_zero (&fdsocket);
Fd_set (Slisten, &fdsocket);
while (TRUE)
{
2. Pass a copy of the collection to the Select function
When an event occurs, select removes the pending socket, and then returns the socket that is the event that occurs when the select is returned.
Fd_set fdread = Fdsocket;
int nret =:: Select (0, &fdread, NULL, NULL, NULL);
if (Nret > 0)
{
By comparing the original Fdsocket set with the processed Fdread collection
for (UINT i=0;i<fdsocket.fd_count;i++)
{
if (Fd_isset (Fdsocket.fd_array[i], &fdread))//That's the trigger.
{
if (fdsocket.fd_array[i] = = Slisten)//Listen sockets receive a new connection for God the horse is divided into two situations: there are two kinds of situations that trigger the Read collection: There is a connection or the data is readable ....
{
//
if (Fdsocket.fd_count < fd_setsize)//fd_setsize=64
{
sockaddr_in addrremote = {0};
int naddrlen = sizeof (addrremote);
SOCKET snew =:: Accept (Slisten, (sockaddr*) &addrremote, &naddrlen);
Fd_set (Snew, &fdsocket);
}
Else
{
printf ("Too many Connection...error");
Continue
}
}
else//have readable
{
Char szcontent[256]={0};
int nrecv =:: Recv (Fdsocket.fd_array[i], szcontent, sizeof (szcontent), 0);
if (Nrecv > 0)
{
SZCONTENT[NRECV] = ' the ';
printf ("Recv data:%s", szcontent);
}
else//did not read the data
{
:: Closesocket (Fdsocket.fd_array[i]);
FD_CLR (Fdsocket.fd_array[i], &fdsocket);
}
}
}
}
}
Else
{
printf ("nret litter 0, error ...");
Return
}
}
:: Closesocket (Slisten); Pair with socket write
printf ("*******************************");
GetChar ();
}
The effect is shown in the following illustration:
I hope this article will help you with the C + + program design.