Exemplo n.º 1
0
	DWORD WINAPI ThreadProc(LPVOID lpParameter)		//接收数据包线程函数
	{
		ThreadParam* param = (ThreadParam*) lpParameter;
		SOCKET s = param->m_s;
		OnMsgComeEvent callback =  param->m_fun;
			
		delete param;
		
		PACKAGE package;

		SOCKADDR_IN addrClient;
		int len=sizeof(SOCKADDR);

		int revlength = 0;
		int length;
		
		int recvlen = 0;

		while (true)
		{
			int recvlen = recvfrom(s, package.Getdata(0),sizeof(PACKAGE), 0, (SOCKADDR*)&addrClient, &len);	//接收包中的前四个字节 得到包长度		
			
			if (recvlen == package.GetLength())		//接收到一个包	UDP不会粘包
			{
				callback(addrClient.sin_addr.S_un.S_addr, package);
			}
		}
		return 0;
	}
Exemplo n.º 2
0
	//发送数据
	extern "C" INETWORK_API bool SendMessage( PACKAGE& msg, int port /*= 3250*/, unsigned long RecverIP /*= NULL*/ )	
	{
		if (0 == CNetWork::g_SendSocket)
		{
			CNetWork::InitWinSokcet();
		}

		SOCKADDR_IN addrSrv;
		if(0 == RecverIP)
		{
			addrSrv.sin_addr = CNetWork::g_Broadcastaddr;
		}
		else
		{
			addrSrv.sin_addr.S_un.S_addr= RecverIP;
		}

		addrSrv.sin_family=AF_INET;
		addrSrv.sin_port=htons(port);

		int len = sendto(CNetWork::g_SendSocket, msg.Getdata(0), msg.GetLength(), 0,
			(SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
		return true;
	}