[Windows]7 kind of network programming I/O model Code implementation Instance __ programming

Source: Internet
Author: User
Tags sin htons

from:http://blog.csdn.net/woshinia/article/details/8585930

Some of the code refers to [Windows Network and Communication programming]. Wang Yanping, the code of some I/O models in the network does not have a deep research on whether the socket can be written, I will provide some solutions.

In blocking mode, send will be blocked (in non-blocking mode send return wsaewouldblock error, overlapped I/O performance for the delivery request has been unable to complete) situation can generally be divided into 3 kinds:

1, although the server sent a large amount of data, but the client did not call the Recv function to answer.

2, the network condition is poor, send the data in the buffer has not been sent out.

3, the amount of data sent is very large, such as the download function, the protocol sent data is not as fast as the Send function to copy the data to the sending buffer speed.

For 1,2 cases, it seems that we can simply close the socket and let the client request it again. But for 3, it doesn't work. And in the actual operation process, we cannot distinguish is 1, 2, or 3, we can do is as far as possible to ensure the correctness of the transmission. Of course, to prevent 1 conditions or 2 of the time network is not smooth, you can set the timeout. If the socket has been in an writable state for more than 1 minutes, then close the socket. This timeout mechanism is added to the final IOCP model. Other models to join, you can refer to it to do.


One, the basic blocking model

[CPP]View Plain copy print? #include <WinSock2.h> #include <Windows.h> #include <stdio.h> #pragma comment (lib, "Ws2_32.li B ")DWORDWINAPI Workthread (void* param) {socket* psclient = (socket*) param;CharBUF[4096]; while(true)       {intLen = recv (*psclient,buf,4096,0);if(Len <= 0) {printf ("recv failed.)               %d\n ", WSAGetLastError ()); Sleep (5000); Break;           } Buf[len] = ';       printf ("Received data:%s\n", buf); } closesocket (*psclient);DeletePsclient; return0; }intMain () {wsadata wsadata;if(0!= WSAStartup (Makeword (2,2), &wsadata)) {printf ("WSAStartup failed.)           \ n ", WSAGetLastError ()); Sleep (5000); return0; }USHORTNport = 3456;       Socket Slisten = socket (AF_INET,SOCK_STREAM,IPPROTO_TCP);       Sockaddr_in sin;       sin.sin_family = af_inet;       Sin.sin_port = htons (nport); Sin.sin_addr. S_un. S_ADDR = Inaddr_any;if(Socket_error =: Bind (Slisten, sockaddr*) &sin,sizeof(sin)) {printf ("bind failed.")           %d\n ", WSAGetLastError ()); Sleep (5000); return-1; }:: Listen (slisten,5); while(true) {sockaddr_in addrremote;intNaddrlen =sizeof(Addrremote); SOCKET *psclient =NewSOCKET; *psclient = Accept (Slisten, (sockaddr*) &addrremote,&naddrlen);HANDLE hthread = createthread (null,0,workthread,psclient,0,null);            closehandle (hthread);       }        closesocket (Slisten);       wsacleanup ();  }  

#include <WinSock2.h> #include <Windows.h> #include <stdio.h> #pragma comment (lib, "Ws2_32.lib")
	DWORD winapi Workthread (void* param) {socket* psclient = (socket*) param;
	Char buf[4096];
		while (true) {int len = recv (*psclient,buf,4096,0); if (len <= 0) {printf ("recv) failed.
			%d\n ", WSAGetLastError ());
			Sleep (5000);
		Break
		} Buf[len] = ';
	printf ("Received data:%s\n", buf);
	} closesocket (*psclient);
	Delete psclient;
return 0;
	int main () {wsadata wsadata; if (0!= WSAStartup (Makeword (2,2), &wsadata)) {printf (WSAStartup) failed.
		\ n ", WSAGetLastError ());
		Sleep (5000);
	return 0;
	} USHORT nport = 3456;
	Socket Slisten = socket (AF_INET,SOCK_STREAM,IPPROTO_TCP);
	Sockaddr_in sin;
	sin.sin_family = af_inet;
	Sin.sin_port = htons (nport); Sin.sin_addr. S_un.

	S_ADDR = Inaddr_any; if (Socket_error =:: Bind (Slisten, (sockaddr*) &sin,sizeof (sin)) {printf ("bind failed.")
		%d\n ", WSAGetLastError ());
		Sleep (5000);
	return-1;

	}:: Listen (slisten,5); Whiletrue) {sockaddr_in addrremote;
		int naddrlen = sizeof (addrremote);
		Socket *psclient = new Socket;
		*psclient = Accept (Slisten, (sockaddr*) &addrremote,&naddrlen);
		HANDLE hthread = CreateThread (null,0,workthread,psclient,0,null);
	CloseHandle (Hthread);
	} closesocket (Slisten);
WSACleanup (); }

Second, no optimal non-blocking model

[CPP]View Plain copy print? #include <WinSock2.h> #include <Windows.h> #include <stdio.h> #include <vector>usingnamespaceStd #pragma comment (lib, "Ws2_32.lib") critical_section G_cs;HANDLEG_startevent; Vector<socket> g_vecclients;intg_ivecsize = 0;DWORDWINAPI Workthread (void* param) {CharBUF[4096]; while(1) {if(G_vecclients.empty ())               {resetevent (g_startevent);           WaitForSingleObject (G_startevent,infinite); } entercriticalsection (&g_cs); for(Vector<socket>::iterator it = G_vecclients.begin (); it!= g_vecclients.end ();) {intLen = recv (*it,buf,4096,0);if(len = = socket_error) {if(Wsaewouldblock!= WSAGetLastError ())                       {printf ("recv error:%d\n", WSAGetLastError ());                       Closesocket (*it);                   it = g_vecclients.erase (it); }Else{printf ("%d.", *it);                   ++it; }               }Else{Buf[len] = 0;                   printf ("Received data:%s\n", buf);               ++it;           } leavecriticalsection (&g_cs);          Sleep (100); } return0; }intMain () {initializecriticalsectionandspincount (&g_cs,4000);          G_startevent = CreateEvent (null,false,false,null);       Wsadata wsadate; WSAStartup (Makeword (2,2), &wsadate);USHORTNport = 3456;       U_long ul = 1;       Socket s = socket (af_inet,sock_stream,0);       Ioctlsocket (S,fionbio,&ul);       Sockaddr_in sin;       sin.sin_family = af_inet;       Sin.sin_port = htons (nport); Sin.sin_addr. S_un. S_ADDR = Addr_any;if(Socket_error =: Bind (s, (sockaddr*) &sin,sizeof(sin)) { return-1; }:: Listen (s,5);HANDLEHthread = CreateThread (null,0,workthread,null,0,null); CloseHandle (Hthread); while(true) {sockaddr_in addrremote;intNaddrlen =sizeof(Addrremote); SOCKET sclient = Accept (S, (sockaddr*) &addrremote,&naddrlen);if(Sclient!= Socket_error)               {entercriticalsection (&AMP;G_CS);               G_vecclients.push_back (sclient); LeaveCriticalSection (&g_cs);if(G_vecclients.size () = 1)           SetEvent (g_startevent); }Elseif(Wsaewouldblock = = WSAGetLastError ())               {printf (".");           Sleep (100); }Else           {                printf ("accept failed! %d\n", WSAGetLastError ());           }       }        closesocket (s);       wsacleanup ();        closehandle (g_startevent);       deletecriticalsection (&g_cs);   }  

#include <WinSock2.h> #include <Windows.h> #include <stdio.h> #include <vector> using namespace

Std
#pragma comment (lib, "Ws2_32.lib") critical_section G_cs;
HANDLE g_startevent;
Vector<socket> g_vecclients;
int g_ivecsize = 0;
	DWORD winapi Workthread (void* param) {char buf[4096];
			while (1) {if (G_vecclients.empty ()) {resetevent (g_startevent);
		WaitForSingleObject (G_startevent,infinite);
		} entercriticalsection (&g_cs);
		for (Vector<socket>::iterator it = G_vecclients.begin (); it!= g_vecclients.end ();)
			{int len = recv (*it,buf,4096,0); if (len = = Socket_error) {if (Wsaewouldblock!= wsagetlasterror ()) {printf ("recv error:%d\n", Wsagetlasterr
					or ());
					Closesocket (*it);
				it = g_vecclients.erase (it);
					else {printf ("%d.", *it);
				++it;
				} else {Buf[len] = 0;
				printf ("Received data:%s\n", buf);
			++it;
		} leavecriticalsection (&g_cs);
Sleep (100);
	return 0;
	int main () {initializecriticalsectionandspincount (&g_cs,4000);

	G_startevent = CreateEvent (null,false,false,null);
	Wsadata wsadate;
	WSAStartup (Makeword (2,2), &wsadate);
	USHORT nport = 3456;
	U_long ul = 1;
	Socket s = socket (af_inet,sock_stream,0);
	Ioctlsocket (S,fionbio,&ul);
	Sockaddr_in sin;
	sin.sin_family = af_inet;
	Sin.sin_port = htons (nport); Sin.sin_addr. S_un.

	S_ADDR = Addr_any;
	if (Socket_error =:: Bind (S, (sockaddr*) &sin,sizeof (sin)) {return-1;

	}:: Listen (s,5);
	HANDLE hthread = CreateThread (null,0,workthread,null,0,null);

	CloseHandle (Hthread);
		while (true) {sockaddr_in addrremote;
		int naddrlen = sizeof (addrremote);
		SOCKET sclient = Accept (S, (sockaddr*) &addrremote,&naddrlen);
			if (sclient!= socket_error) {entercriticalsection (&AMP;G_CS);
			G_vecclients.push_back (sclient);
			LeaveCriticalSection (&g_cs);
		if (g_vecclients.size () = = 1) setevent (g_startevent); else if (Wsaewouldblock = = WSAgetlasterror ()) {printf (".");
		Sleep (100); else {printf ("Accept failed!
		%d\n ", WSAGetLastError ());
	} closesocket (s);
	WSACleanup ();
	CloseHandle (g_startevent);
DeleteCriticalSection (&g_cs); }

Three, select model


[CPP] view plain copy print? #include <WinSock2.h> #include <Windows.h> #include <MSWSock.h> #include <stdio.h> #in Clude <map> using

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.