Exploring the select Io Model

Source: Internet
Author: User

Wsadata wsdata;
If (wsastartup (makeword (2, 2), & wsdata ))
{
Trace ("initialization failed ");

}

Socket sersock = socket (af_inet, sock_stream, 0 );
If (sersock = socket_error)
{

Trace ("failed to create socket ");
Wsacleanup ();
}

Sockaddr_in ADDR;
ADDR. sin_family = af_inet;
ADDR. sin_port = htons (5005 );
ADDR. sin_addr.s_un.s_addr = inet_addr ("127.0.0.1 ");

If (BIND (sersock, (sockaddr *) & ADDR, sizeof (ADDR) = socket_error)
{
Trace ("failed to create socket ");
Wsacleanup ();
}

If (Listen (sersock, 5) = socket_error)
{
Trace ("socket listener failed ");
Wsacleanup ();
}

Socket clisock;
Sockaddr_in cliaddr;

Int Len = sizeof (cliaddr );
Char Buf [maxbulen];
G_bready = true;

Fd_set fd_read;
Fd_zero (& fd_read );

Timeval TV;
TV. TV _sec = 2;
TV. TV _usec = 0;
Int res;
While (1)
{
Fd_set (sersock, & fd_read); // Add the listening socket to the readable model.
// G_itotalcli + = 1;

// Add link detection to delete the disconnected socket

 

For (INT I = 0; I <g_itotalcli; I ++)
{
Fd_set (g_clisocketarr [I], & fd_read );
}

Res = select (null, & fd_read, null, null, & TV );
Trace ("select called, Return Value % d \ n", Res );
If (RES = 0)
{
Continue; // timeout
}

If (fd_isset (sersock, & fd_read ))
{
Trace ("new connections are coming! \ N ");
Clisock = accept (sersock, (sockaddr *) & cliaddr, & Len );
G_clisocketarr [g_itotalcli ++] = clisock; // accepts the connection.
}

For (INT I = 0; I <g_itotalcli; I ++)
{
If (fd_isset (g_clisocketarr [I], & fd_read ))
{
Memset (BUF, 0, maxbulen );
Int recvres = Recv (g_clisocketarr [I], Buf, maxbulen, 0 );
If (recvres = 0 | (RES = socket_error & wsagetlasterror () = wsaeconnreset ))
{
Trace ("socket closed! \ N ");
Closesocket (g_clisocketarr [I]);
If (I <g_itotalcli-1)
{
G_clisocketarr [I --] = g_clisocketarr [-- g_itotalcli];
}
}
Else
{
Buf [recvres] = '\ 0 ';
Trace ("received message: % s \ n", Buf );
}
}
}
}
Return 0;

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.