Winsock Overlapped IO模型(一) (转)

转载 2016年08月30日 21:46:29
// NetWork.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <Winsock2.h>
#include <Windows.h>
#include <process.h>
#pragma comment(lib, "WS2_32.lib")

#define MAX_BUFFER	256
#define MAX_TIMEOUT 1000

typedef enum _OPERATION_INFO
{
	OP_NULL,
	OP_READ,
	OP_WRITE
}OPERATIONINFO;

typedef struct _OVERLAPPED_INFO_
{	
public:
	_OVERLAPPED_INFO_()
	{
		Clean();
	}
	~_OVERLAPPED_INFO_()
	{
		Clean();
	}
protected:
	void Clean()
	{
		ol.hEvent = NULL;
		sock = INVALID_SOCKET;
		memset(&addr, 0, sizeof(addr));
		addr.sin_addr.S_un.S_addr = INADDR_ANY;
		addr.sin_family = AF_INET;
		addr.sin_port = htons(0);
		wsaBuf.buf = szBuf;
		wsaBuf.len = MAX_BUFFER;
		memset(szBuf, 0, sizeof(szBuf));
		nOpType = OP_NULL;
	}
public:
	WSAOVERLAPPED ol;
	SOCKET sock;
	SOCKADDR_IN addr;
	WSABUF wsaBuf;
	char szBuf[MAX_BUFFER];
	OPERATIONINFO nOpType;
}OVERLAPPEDINFO, *POVERLAPPEDINFO;

WSAEVENT g_event[WSA_MAXIMUM_WAIT_EVENTS] = {0};
OVERLAPPEDINFO* g_ol[WSA_MAXIMUM_WAIT_EVENTS] = {0};
int g_nIndex = 0;
BOOL g_bExitThread = FALSE;

unsigned __stdcall ThreadProc(LPVOID lParam);

int _tmain(int argc, _TCHAR* argv[])
{
	WSADATA wsaData;
	if(0 != WSAStartup(MAKEWORD(2, 2), &wsaData))
	{
		printf("WSAStartup failed with error code: %d/n", GetLastError());
		return EXIT_FAILURE;
	}
	if(2 != HIBYTE(wsaData.wVersion) || 2 != LOBYTE(wsaData.wVersion))
	{
		printf("Socket version not supported./n");
		WSACleanup();
		return EXIT_FAILURE;
	}
	SOCKET sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(INVALID_SOCKET == sListen)
	{
		printf("socket failed with error code: %d/n", WSAGetLastError());
		WSACleanup();
		return EXIT_FAILURE;
	}
	SOCKADDR_IN addr = {0};
	addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addr.sin_family = AF_INET;
	addr.sin_port = htons(5050);
	if(SOCKET_ERROR == bind(sListen, (LPSOCKADDR)&addr, sizeof(addr)))
	{
		printf("bind failed with error code: %d/n", WSAGetLastError());
		closesocket(sListen);
		sListen = INVALID_SOCKET;
		WSACleanup();
		return EXIT_FAILURE;
	}
	if(SOCKET_ERROR == listen(sListen, 5))
	{
		printf("listen failed with error code: %d/n", WSAGetLastError());
		closesocket(sListen);
		sListen = INVALID_SOCKET;
		WSACleanup();
		return EXIT_FAILURE;
	}
	HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, 0, NULL);
	if(NULL == hThread)
	{
		printf("_beginthreadex failed with error code: %d/n", GetLastError());
		closesocket(sListen);
		sListen = INVALID_SOCKET;
		WSACleanup();
		return EXIT_FAILURE;
	}
	
	printf("Server start listen and wait for client to connect .../n");

	SOCKADDR_IN remote = {0};
	int len = sizeof(remote);

	while(TRUE)
	{
		if(g_nIndex >= WSA_MAXIMUM_WAIT_EVENTS)
		{
			printf("Too many connect, wait for disconnect .../n");
			continue;
		}
		SOCKET sNew = accept(sListen, (LPSOCKADDR)&remote, &len);
		if(INVALID_SOCKET == sNew)
		{
			printf("accept failed with error code: %d/n", WSAGetLastError());
			continue;
		}
		printf("<IP: %s, Port: %d> client come in./n", inet_ntoa(remote.sin_addr), ntohs(remote.sin_port));
		DWORD dwTrans = 0;
		DWORD dwFlags = 0;
		g_ol[g_nIndex] = new OVERLAPPEDINFO;
		g_ol[g_nIndex]->sock = sNew;
		memcpy(&g_ol[g_nIndex]->addr, &remote, sizeof(remote));
		g_event[g_nIndex] = g_ol[g_nIndex]->ol.hEvent = WSACreateEvent();
		g_ol[g_nIndex]->nOpType = OP_READ;
		if(SOCKET_ERROR == WSARecv(g_ol[g_nIndex]->sock, &(g_ol[g_nIndex]->wsaBuf), 1, &dwTrans, &dwFlags, (LPWSAOVERLAPPED)&(g_ol[g_nIndex]->ol), NULL))
		{
			if(ERROR_IO_PENDING != WSAGetLastError())
			{
				printf("WSARecv failed with error code: %d/n", WSAGetLastError());
				closesocket(g_ol[g_nIndex]->sock);
				delete g_ol[g_nIndex];
				g_ol[g_nIndex] = NULL;
				continue;
			}
		}
		g_nIndex++;
	}
	// End of thread and exit process
	g_bExitThread = TRUE; // Exit thread.
	WaitForSingleObject(hThread, INFINITE);
	CloseHandle(hThread);

	WSACleanup();
	return 0;
}

unsigned __stdcall ThreadProc(LPVOID lParam)
{
	while(!g_bExitThread)
	{
		DWORD dwTrans = 0;
		DWORD dwFlags = 0;
		DWORD dwIndex = WSAWaitForMultipleEvents(g_nIndex, g_event, FALSE, MAX_TIMEOUT, FALSE);
		if(WSA_WAIT_FAILED == dwIndex || WSA_WAIT_TIMEOUT == dwIndex)
		{
			continue;
		}
		
		dwIndex -= WSA_WAIT_EVENT_0;
		for(int i = dwIndex; i < g_nIndex; i++)
		{
			dwIndex = WSAWaitForMultipleEvents(1, &g_event[dwIndex], TRUE, INFINITE, FALSE);
			if(WSA_WAIT_FAILED == dwIndex)
			{
				continue;
			}
			dwIndex -= WSA_WAIT_EVENT_0;
			WSAResetEvent(g_event[dwIndex]);
			BOOL bRet = WSAGetOverlappedResult(g_ol[dwIndex]->sock, &(g_ol[dwIndex]->ol), &dwTrans, FALSE, &dwFlags);
			if(bRet)
			{
				if(dwTrans > 0)
				{
					switch(g_ol[dwIndex]->nOpType)
					{
					case OP_READ:
						{
							printf("recv client <%s:%d> data: %s/n", inet_ntoa(g_ol[dwIndex]->addr.sin_addr), ntohs(g_ol[dwIndex]->addr.sin_port), g_ol[dwIndex]->szBuf);
							g_ol[dwIndex]->nOpType = OP_WRITE;
							memset(&(g_ol[dwIndex]->ol), 0, sizeof(g_ol[dwIndex]->ol));
							if(SOCKET_ERROR == WSASend(g_ol[dwIndex]->sock, &(g_ol[dwIndex]->wsaBuf), 1, &dwTrans, dwFlags, &(g_ol[dwIndex]->ol), NULL))
							{
								if(ERROR_IO_PENDING != WSAGetLastError())
								{
									printf("WSASend failed with error code: %d/n", WSAGetLastError());
									continue;
								}
							}
						}
						break;

					case OP_WRITE:
						{
							g_ol[dwIndex]->nOpType = OP_READ;
							memset(&(g_ol[dwIndex]->ol), 0, sizeof(g_ol[dwIndex]->ol));
							memset(g_ol[dwIndex]->szBuf, 0, sizeof(g_ol[dwIndex]->szBuf));
							dwFlags = 0;
							g_ol[dwIndex]->wsaBuf.buf = g_ol[dwIndex]->szBuf;
							dwTrans = g_ol[dwIndex]->wsaBuf.len = MAX_BUFFER;
							if(SOCKET_ERROR == WSARecv(g_ol[dwIndex]->sock, &(g_ol[dwIndex]->wsaBuf), 1, &dwTrans, &dwFlags, &(g_ol[dwIndex]->ol), NULL))
							{
								if(ERROR_IO_PENDING != WSAGetLastError())
								{
									printf("WSARecv failed with error code: %d/n", WSAGetLastError());
									continue;
								}
							}
						}
						break;

					default:
						break;
					}				
				}
				else
				{
					printf("client <%s : %d> leave./n", inet_ntoa(g_ol[dwIndex]->addr.sin_addr), ntohs(g_ol[dwIndex]->addr.sin_port));
					closesocket(g_ol[dwIndex]->sock);
					WSACloseEvent(g_event[dwIndex]);
					delete g_ol[dwIndex];
					// Rebuild array
					for(int i= dwIndex; i<g_nIndex-1; i++)
					{
						g_event[i] = g_event[i+1];
						g_ol[i] = g_ol[i+1];
					}
					g_nIndex--;
				}
			}
			else
			{
				printf("WSAGetOverlappedResult failed with error: %d/n", WSAGetLastError());
			}
		}
	}
	printf("Server to exit ... /n");

	return 0;
}


转自:http://blog.csdn.net/visualeleven/article/details/5991743

相关文章推荐

Winsock IO模型之Overlapped模型

这个模型的基本思想是使用重叠数据结构一次投递一个或多个异步I/O请求。当提交的I/O请求完成之后,与之关联的重叠数据结构中的事件对象受信,应用程序便可使用WSAGetOverlappedResult函...

Winsock 网络编程 Socket模型之Overlapped模型

前言: 讲一下套接字模式和套接字I/O模型的区别。先说明一下,只针对Winsock 套接字模式:阻塞套接字和非阻塞套接字。或是叫同步套接字和异步套接字。 套接字模型:描述如何对套接字的I/O...

串口通讯编程一日通2(Overlapped IO模型)

第一篇初步了解串口的大致运作,接下来我们看基本操作 先看串口操作的数据结构: 串口操作有几个比较重要的Struct 1.Overlapped I/O 异步I/O模型 异步I/O...

异步IO模型和Overlapped结构

转自:http://space.itpub.net/25897606/viewspace-705867 OVERLAPPED结构主要用于异步I/O操作,其数据结构定义如下: typedef s...
  • lg2lh
  • lg2lh
  • 2012年03月07日 11:34
  • 798

SOCKET编程进阶之Overlapped IO完成例程模型

SOCKET编程进阶之Overlapped IO完成例程模型 完成例程模型相比与事件通知模型有个很大的优点就是不再受64个消息的限制,一个线程可以同时管理成百上千个socket连接,且保持较高的性能...
  • zsJum
  • zsJum
  • 2011年11月18日 14:35
  • 924

Socket编程模型之重叠IO(Overlapped I/O)模型

Winsock2的发布使得Socket I/O有了和文件I/O统一的接口。我们可以通过使用Win32文件操纵函数ReadFile和WriteFile来进行Socket I/O。伴随而来的,用于普通文件...

WinSock IO模型三: WSAEventSelect 事件机制

WSAEventSelect模型是WindowsSockets提供的一个有用异步I/O模型。该模型允许在一个或者多个套接字上接收以事件为基础的网络事件通知。Windows Sockets应用程序在创建...
  • zhu2695
  • zhu2695
  • 2013年03月19日 23:34
  • 741

WinSock IO模型四: 重叠I/O (完成例程)

完成例程模型相比与事件通知模型有个很大的优点就是不再受64个消息的限制,一个线程可以同时管理成百上千个socket连接,且保持较高的性能。  完成例程相比与完成端口较为逊色,因为它的性能不能随着系统...
  • zhu2695
  • zhu2695
  • 2013年03月24日 12:12
  • 833

Winsock IO模型

  • 2011年10月19日 20:43
  • 34KB
  • 下载

WinSock IO模型五: 完成端口

众所皆知,完成端口是在WINDOWS平台下效率最高,扩展性最好的IO模型,特别针对于WINSOCK的海量连接时,更能显示出其威力。 众所皆知,完成端口是在WINDOWS平台下效率最高,扩展性最好...
  • zhu2695
  • zhu2695
  • 2013年03月24日 12:30
  • 644
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Winsock Overlapped IO模型(一) (转)
举报原因:
原因补充:

(最多只允许输入30个字)