葡京网投哪个正规 > 首页 > TCP客户端加2个UDP端口_接收数据有问题,VC视频教程笔记葡京网投哪个正规:

原标题:TCP客户端加2个UDP端口_接收数据有问题,VC视频教程笔记葡京网投哪个正规:

浏览次数:141 时间:2020-03-25

第16课
1.风云指标:来落实线程的联手。与排挤对象近似均属于基本对象。
             当人工重新初始化有复信号时,所有线程均拿走连续信号,所以不能设为人工重新设置。代码就不贴了。
             通过创造无名的事件目的,也能够让三个程序只好运转二个实例。  
2.首要代码段达成线程的一道:相符公用电话亭,唯有当电话亭里面没人了,别的人技巧够再进来打电话。用了4个函数,这种情势比较简单!但瑕玷是借使使用了轻微关键代码码,轻便赞成线程的死锁
3.线程死锁,用关键代码示例,用了八个临界区目的,实战中要在意幸免这种不当!
4.施用异步套接字编写互连网谈心室
   1State of Qatar加载套接字库,举办版本协商,包涵头文件,链接库文件,此番请示的是2.2本子!
   2)在类CChatDlg中加进三个成员变量m_socket,在析构函数中放出那些变量
   3)利用WSASocket(卡塔尔(قطر‎制造套接字(数据报类型的UDP型的)
   4)然后调用WSAAsyncSelect(m_socket,m_hWnd,UM_SOCK,FD_READ卡塔尔国为网络事件定义新闻!那时候假如爆发FD_READ音信,系统会发送UM_SOCK新闻给应用程序!程序并不会卡住在这里儿了!
   以上是在BOOL CChatDlg::OnInitDialog(卡塔尔(قطر‎达成
   5)然后成功消息响应!
   头文件中:#define UM_SOCK   WM_USER+1
afx_msg void OnSock(WPARAM,LPARAM);
    源文件中:
     ON_MESSAGE(UM_SOCK,OnSock)
     完毕音讯响应函数:void CChatDlg::OnSock(WPARAM wParam,LPARAM lParam卡塔尔(قطر‎
{
switch(LOWORD(lParam))
{
case FD_READ:
   WSABUF wsabuf;
   wsabuf.buf=new char[200];
   wsabuf.len=200;
   DWORD dwRead;
   DWORD dwFlag=0;
   SOCKADDR_IN addrFrom;
   int len=sizeof(SOCKADDR);
   CString str;
   CString strTemp;
   HOSTENT *pHost;
   if(SOCKET_ERROR==WSARecvFrom(m_socket,&wsabuf,1,&dwRead,&dwFlag,
       (SOCKADDR*)&addrFrom,&len,NULL,NULL))
   {
    MessageBox("采纳数据退步!"卡塔尔国;
    return;
   }
   pHost=gethostbyaddr((char*)&addrFrom.sin_addr.S_un.S_addr,4,AF_INET);
   //str.Format("%s说 :%s",inet_ntoa(addrFrom.sin_addr),wsabuf.buf);
   str.Format("%s说 :%s",pHost->h_name,wsabuf.buf);
   str+="rn";
   GetDlgItemText(IDC_EDIT_RECV,strTemp);
   str+=strTemp;
   SetDlgItemText(IDC_EDIT_RECV,str);
   break;
}
}
OK!
       6)实现数据发送的法力!
       void CChatDlg::OnBtnSend()
{
// TOD Add your control notification handler code here
DWORD dwIP;
CString strSend;
WSABUF wsabuf;
DWORD dwSend;
int len;
CString strHostName;
SOCKADDR_IN addrTo;
HOSTENT* pHost;
if(GetDlgItemText(IDC_EDIT_HOSTNAME,strHostName),strHostName=="")
{
   ((CIPAddressCtrl*)GetDlgItem(IDC_IPADDRESS1))->GetAddress(dwIP);
   addrTo.sin_addr.S_un.S_addr=htonl(dwIP);
}
else
{
   pHost=gethostbyname(strHostName);
   addrTo.sin_addr.S_un.S_addr=*((DWORD*)pHost->h_addr_list[0]);
}

第15课三十二线程与网络编制程序
1.七十八线程介绍,略
2.贰个简便的十二线程程序
MSND中参数[in]和[out]的含义要小心
#include <windows.h>
#include <iostream.h>

眼下要用MFC写三个互联网程序,完结同一个IPTCP客户端2个UDP端口而且收发数据蒙受了一个难点:UDP1采取的多寡有的时候会跑到UDP2那边,请问是何等原因吗,笔者贴出部分代码?//建立SOCKETsocket_udp=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);socket_udp2=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);socket_tcp_client=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);addr_tcp_target.sin_family=AF_INET;addr_udp_target.sin_family=AF_INET;addr_udp_target2.sin_family=AF_INET;this-GetDlgItem(IDC_IPADDRESS1)-GetWindowText(str1);this-GetDlgItem(IDC_PORT1_EDIT)-GetWindowText(str2);this-GetDlgItem(IDC_PORT2_EDIT)-GetWindowText(str3);this-GetDlgItem(IDC_PORT3_EDIT)-GetWindowText(str3);m_port1=atoi(str2.GetBuffer(1));m_port2=atoi(str3.GetBuffer(1));m_port3=atoi(str4.GetBuffer(1));//tcpaddr_tcp_target.sin_port=ntohs(m_port1);//htons(3000);//m_portaddr_tcp_target.sin_addr.S_un.S_addr=inet_addr(str1.GetBuffer(1));//m_ip//udpaddr_udp_target.sin_port=ntohs(m_port2);//htons(3001);//m_portaddr_udp_target.sin_addr.S_un.S_addr=inet_addr(str1.GetBuffer(1));//m_ipaddr_udp_target2.sin_port=ntohs(m_port3);//htons(3002);//m_portaddr_udp_target2.sin_addr.S_un.S_addr=inet_addr(str1.GetBuffer(1));//m_ip//localipportgethostname(hostname,sizeof(hostname));hostent*hn;hn=gethostbyname(hostnameState of Qatar;//依据本机主机名获得本机ipstrIPAddr=inet_ntoa(*(structin_addr*)hn-h_addr_list[0]卡塔尔国;//把ip换到字符串情势//tcpaddr_tcp.sin_family=AF_INET;addr_tcp.sin_addr.S_un.S_addr=inet_addr(strIPAddr卡塔尔(قطر‎;//顾客端地址addr_tcp.sin_port=htons(3000卡塔尔国;//TCP顾客端为3000端口bind(socket_tcp_client,(SOCKADDR*)addr_tcp,sizeof(SOCKADDCR-V卡塔尔(قطر‎卡塔尔(قطر‎;//顾客端绑定//udpaddr_udp.sin_family=AF_INET;addr_udp.sin_addr.S_un.S_addr=inet_addr(strIPAddrState of Qatar;//客户端地址addr_udp.sin_port=htons(3001);//本地UDP为3001端口bind(socket_udp,(SOCKADDR*)addr_udp,sizeof(SOCKADD宝马X3State of Qatar卡塔尔国;//客商端绑定addr_udp2.sin_family=AF_INET;addr_udp2.sin_addr.S_un.S_addr=inet_addr(strIPAddrState of Qatar;//顾客端地址addr_udp2.sin_port=htons(3002);//本地UDP为3001端口bind(socket_udp2,(SOCKADDR*)addr_udp2,sizeof(SOCKADDCRUISER卡塔尔国卡塔尔(قطر‎;//顾客端绑定//异步设置if(WSAAsyncSelect(socket_tcp_client,this-m_hWnd,WM_SOCKET,FD_READ)){MessageBox(_T("tcp异步设置出错"卡塔尔,_T(""));}if(WSAAsyncSelect(socket_udp,this-m_hWnd,WM_SOCKET,FD_READ)){MessageBox(_T("udp异步设置出错"卡塔尔(قطر‎,_T(""));}if(WSAAsyncSelect(socket_udp2,this-m_hWnd,WM_SOCKET,FD_READ)){MessageBox(_T("udp2异步设置出错"State of Qatar,_T(""卡塔尔(قطر‎卡塔尔;}//作者自定义了三个新闻OnSocket(WPARAMwParam,LPARAMlParamState of Qatar选用3个端口数据ret1=recv(socket_tcp_client,buff_tcp,146000,NULL);intn=sizeof(addr_udp_target);ret2=recvfrom(socket_udp,buff_udp,146000,0,(sockaddr*)addr_udp_target,n);intn2=sizeof(addr_udp_target2);ret3=recvfrom(socket_udp2,buff_udp2,146000,0,(sockaddr*)addr_udp_target2,n2);

addrTo.sin_family=AF_INET;
addrTo.sin_port=htons(6000);

DWORD WINAPI Fun1Proc(
   LPVOID lpParameter    // thread data
);

倘使您想在Windows平台上营造服务器应用,那么I/O模型是你必需构思的。Windows操作系统提供了增选(Select)、异步选择(WSAAsyncSelect)、事件接收(WSAEventSelect)、重叠I/O(Overlapped I/O)和实现端口(Completion Port卡塔尔共多样I/O模型。每一样模型均适用于一种特定的利用项景。技术员应该对本身的接收须要格外生硬,并且综合酌量到程序的扩大性和可移植性等成分,作出本身的选取。

GetDlgItemText(IDC_EDIT_SEND,strSend);
len=strSend.GetLength();
wsabuf.buf=strSend.GetBuffer(len);
wsabuf.len=len+1;

DWORD WINAPI Fun2Proc(
   LPVOID lpParameter    // thread data
);
int index=0;
int tickets=100;
HANDLE hMutex;互斥对象的句柄
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL卡塔尔国;创立线程1
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL卡塔尔;创造线程2
CloseHandle(hThread1卡塔尔国;关闭线程的句柄,为何要关张?它将线程的运用计数减1
CloseHandle(hThread2卡塔尔国;那样当线程截止时,线程内核查象被假释,不然独有当进度甘休,才假释线程的底子对象
/*while(index++<1000)
   cout<<"main thread is running"<<endl;*/
//hMutex=CreateMutex(NULL,TRUE,NULLState of Qatar;将第1个参数设为true后,互斥对象的计数加1
hMutex=CreateMutex(NULL,TRUE,"tickets"卡塔尔国;此段代码能够让系统只一份实例在运作!
if(hMutex)
{
   if(ERROR_ALREADY_EXISTS==GetLastError())
   {
    cout<<"only instance can run!"<<endl;
    return;
   }
}
WaitForSingleObject(hMutex,INFINITEState of Qatar;此代码也将互斥对象的计数加1
ReleaseMutex(hMutex卡塔尔(قطر‎;所以要自由一次互斥对象
ReleaseMutex(hMutex);
Sleep(4000);睡眠4000毫秒
// Sleep(10);
}

笔者会以一个应对反射式服务器(与《Windows网络编制程序》第八章相符)来介绍那多样I/O模型。
大家假使客商端的代码如下(为代码直观,省去全体错误检查,以下同):

SetDlgItemText(IDC_EDIT_SEND,"");

DWORD WINAPI Fun1Proc(
   LPVOID lpParameter    // thread data
)
{
/*while(index++<1000)
   cout<<"thread1 is running"<<endl;*/

#include <WINSOCK2.H>
#include <stdio.h>

if(SOCKET_ERROR==WSASendTo(m_socket,&wsabuf,1,&dwSend,0,
    (SOCKADDR*)&addrTo,sizeof(SOCKADDR),NULL,NULL))
{
   Message博克斯("发送数据退步!"卡塔尔国;
   return;
}

/*while(TRUE)
{
   //ReleaseMutex(hMutex);
   WaitForSingleObject(hMutex,INFINITE卡塔尔国;等待互斥对象的驾临,到来后将互斥对象的计数加1
   if(tickets>0)
   {
    Sleep(1);
    cout<<"thread1 sell ticket : "<<tickets--<<endl;
   }
   else
    break;
   ReleaseMutex(hMutex卡塔尔国;释放互斥对象,将其计数减1,那样能够确定保证,这两句话之间 的代码!的实践一连性!
}*/

#define SERVER_ADDRESS "137.117.2.148"
#define PORT           5150
#define MSGSIZE        1024

}

WaitForSingleObject(hMutex,INFINITE);
cout<<"thread1 is running"<<endl;
return 0;
}

#pragma comment(lib, "ws2_32.lib")

       7)完结将主机名调换为IP地址的职能,从前将IP地址转变为主机名的职能
哈哈哈,单线程的聊天室创制实现!质量况且特别精美!

DWORD WINAPI Fun2Proc(
   LPVOID lpParameter    // thread data
)
{

int main()
{
  WSADATA     wsaData;
  SOCKET      sClient;
  SOCKADDR_IN server;
  char        szMessage[MSGSIZE];
  int         ret;
  
  // Initialize Windows socket library
  WSAStartup(0x0202, &wsaData);

/*while(TRUE)
{
   //ReleaseMutex(hMutex);
   WaitForSingleObject(hMutex,INFINITE);
   if(tickets>0)
   {
    Sleep(1);
    cout<<"thread2 sell ticket : "<<tickets--<<endl;
   }
   else
    break;
   ReleaseMutex(hMutex);
}*/
WaitForSingleObject(hMutex,INFINITE);
cout<<"thread2 is running"<<endl;
return 0;
}

  // Create client socket
  sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

3.多线程谈心程序
   1.加载套接字库在InitInstance(卡塔尔国中,调用AfxSocketInit(卡塔尔(قطر‎,那时能够不加载库文件,但要加入Afxsock.h"头文件
   2.在CChatDlg中开创成员变量m_socket,然后扩展一个分子函数,IniSocket(State of Qatar,在内部完成m_socket的初叶化和绑定。在OnInitDialog中调用InitSocket达成初始化职业。
   3.定义二个构造体,包罗三个参数,sock和hwnd,在OnInitDialog(卡塔尔中最早化这些结构体的目的。
   4.创立三个线程,CreateThread(卡塔尔国,须将线程函数RecvProc定义为静态的要么全局函数。
     ::PostMessage(State of Qatar实现将收到的数额发送给对话框。用自定义的消息,自定义的音信怎么样写?以前说过,参谋上边包车型大巴代码。注意要将EDitBox的MultiLine属性选上。  
     在ChatDlg.h中#define WM_RECVDATA   WM_USER+1
afx_msg void OnRecvData(WPARAM wParam,LPARAM lParam);
     在ChatDlg.cpp中
ON_MESSAGE(WM_RECVDATA,OnRecvData)
下一场达成这么些函数
void CChatDlg::OnRecvData(WPARAM wParam,LPARAM lParam)
{
CString str=(char*)lParam;
CString strTemp;
GetDlgItemText(IDC_EDIT_RECV,strTemp);
str+="rn";
str+=strTemp;
SetDlgItemText(IDC_EDIT_RECV,str);
}
      最后在DWORD WINAPI CChatDlg::RecvProc(LPVOID lpParameter)
中调用 ::PostMessage(hwnd,WM_RECVDATA,0,(LPARAM)tempBuf);
//不能用SendMessage()
     4.对发送按纽的响应代码:
void CChatDlg::OnBtnSend()
{
// TOD Add your control notification handler code here
DWORD dwIP;
((CIPAddressCtrl*)GetDlgItem(IDC_IPADDRESS1))->GetAddress(dwIP);

  // Connect to server
  memset(&server, 0, sizeof(SOCKADDR_IN));
  server.sin_family = AF_INET;
  server.sin_addr.S_un.S_addr = inet_addr(SERVER_ADDRESS);
  server.sin_port = htons(PORT);

SOCKADDR_IN addrTo;
addrTo.sin_family=AF_INET;
addrTo.sin_port=htons(6000);
addrTo.sin_addr.S_un.S_addr=htonl(dwIP);

  connect(sClient, (struct sockaddr *)&server, sizeof(SOCKADDR_IN));

CString strSend;
GetDlgItemText(IDC_EDIT_SEND,strSend);
sendto(m_socket,strSend,strSend.GetLength()+1,0,
   (SOCKADDR*)&addrTo,sizeof(SOCKADDR));
SetDlgItemText(IDC_EDIT_SEND,"");
}

  while (TRUE)
  {
    printf("Send:");
  gets(szMessage);

    // Send message
    send(sClient, szMessage, strlen(szMessage), 0);

    // Receive message
    ret = recv(sClient, szMessage, MSGSIZE, 0);
    szMessage[ret] = '';

    printf("Received [%d bytes]: '%s'n", ret, szMessage);
  }

  // Clean up
  closesocket(sClient);
  WSACleanup();
  return 0;
}

客商端所做的作业一定轻松,创造套接字,连接服务器,然后不停的发送和选择数据。

正如便于想到的一种服务器模型正是行使贰个主线程,担任监听客商端的连年需要,当接过到有些顾客端的总是央求后,创立二个特别用于和该客商端通讯的套接字和贰个救助线程。现在该客商端和服务器的相互都在此个辅助线程内实现。这种情势相比较直观,程序非常轻巧而且可移植性好,可是不能够接受阳台相关的风味。举个例子,固然连接数增加的时候(数不完的连年),那么线程数成倍拉长,操作系统忙于频仍的线程间切换,何况大多数线程在其生命周期内都是高居非活动状态的,那大大浪费了系统的财富。所以,假若你曾经知晓您的代码只会运作在Windows平台上,提出选拔Winsock I/O模型。

一.筛选模型
Select(选取)模型是Winsock中最广大的I/O模型。之所以称其为“Select模型”,是由于它的“主旨情想”正是接纳select函数,完结对I/O的军事拘押。最早安排该模型时,首要面向的是一些使用UNIX操作系统的计算机,它们选择的是伯克利套接字方案。Select模型已合而为一到Winsock 1.1中,它使那多少个想防止在套接字调用进程中被无辜“锁定”的应用程序,选拔一种有序的艺术,同时开展对四个套接字的治本。由于Winsock 1.1向后约等于Berkeley套接字建设方案,所以一旦有叁个伯克利套接字应用使用了select函数,那么从理论角度讲,毋需对其进行任何更换,便可不荒谬运行。(节选自《Windows网络编制程序》第八章卡塔尔
下边包车型客车这段程序正是接收选用模型实现的Echo服务器的代码(已经不可能再简单了):

#include <winsock.h>
#include <stdio.h>

#define PORT       5150
#define MSGSIZE    1024

#pragma comment(lib, "ws2_32.lib")

int    g_iTotalConn = 0;
SOCKET g_CliSocketArr[FD_SETSIZE];

DWORD WINAPI WorkerThread(LPVOID lpParameter);

int main()
{
  WSADATA     wsaData;
  SOCKET      sListen, sClient;
  SOCKADDR_IN local, client;
  int         iaddrSize = sizeof(SOCKADDR_IN);
  DWORD       dwThreadId;

  // Initialize Windows socket library
  WSAStartup(0x0202, &wsaData);

  // Create listening socket
  sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  // Bind
  local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
 local.sin_family = AF_INET;
 local.sin_port = htons(PORT);
  bind(sListen, (struct sockaddr *)&local, sizeof(SOCKADDR_IN));

  // Listen
  listen(sListen, 3);

  // Create worker thread
  CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId); 

  while (TRUE)
  {
    // Accept a connection
    sClient = accept(sListen, (struct sockaddr *)&client, &iaddrSize);
    printf("Accepted client:%s:%dn", inet_ntoa(client.sin_addr), ntohs(client.sin_port));

    // Add socket to fdTotal
    g_CliSocketArr[g_iTotalConn++] = sClient;
  }
  
  return 0;
}

DWORD WINAPI WorkerThread(LPVOID lpParam)
{
  int            i;
  fd_set         fdread;
  int            ret;
  struct timeval tv = {1, 0};
  char           szMessage[MSGSIZE];
  
  while (TRUE)
  {
    FD_ZERO(&fdread);
    for (i = 0; i < g_iTotalConn; i++)
    {
      FD_SET(g_CliSocketArr[i], &fdread);
    }

    // We only care read event
    ret = select(0, &fdread, NULL, NULL, &tv);

    if (ret == 0)
    {
      // Time expired
      continue;
    }

    for (i = 0; i < g_iTotalConn; i++)
    {
      if (FD_ISSET(g_CliSocketArr[i], &fdread))
      {
        // A read event happened on pfdTotal->fd_array[i]
        ret = recv(g_CliSocketArr[i], szMessage, MSGSIZE, 0);
    if (ret == 0 || (ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET))
    {
     // Client socket closed
          printf("Client socket %d closed.n", g_CliSocketArr[i]);
     closesocket(g_CliSocketArr[i]);
     if (i < g_iTotalConn - 1)
          {            
            g_CliSocketArr[i--] = g_CliSocketArr[--g_iTotalConn];
          }
        }
    else
    {
     // We received a message from client
          szMessage[ret] = '';
     send(g_CliSocketArr[i], szMessage, strlen(szMessage), 0);
        }
      }
    }
  }
  
  return 0;
}

服务器的多少个首要动作如下:
1.开立监听套接字,绑定,监听;
2.创立工我线程;
3.开立二个套接字数组,用来存放在当前具备移动的客商端套接字,每accept三个连连就创新一回数组;
4.负责客户端的总是。这里有少数内需专一的,便是自个儿没有再度定义FD_SETSIZE宏,所以服务器最多扶助的并发连接数为64。并且,这里绝对不可以无条件的accept,服务器应该依靠当前的连接数来决定是不是选用来自某些顾客端的一而再三番一遍。一种相比好的兑现方案便是选取WSAAccept函数,而且让WSAAccept回调自己实现的Condition Function。如下所示:

int CALLBACK ConditionFunc(LPWSABUF lpCallerId,LPWSABUF lpCallerData, LPQOS lpSQOS,LPQOS lpGQOS,LPWSABUF lpCalleeId, LPWSABUF lpCalleeData,GROUP FAR * g,DWORD dwCallbackData)
{
 if (当前连接数 < FD_SETSIZE)
  return CF_ACCEPT;
 else
  return CF_REJECT;
}

劳力线程里面是一个死循环,三回巡回完毕的动作是:
1.将近来具有的顾客端套接字参加到读集fdread中;
2.调用select函数;
3.查看有个别套接字是还是不是照旧处在读聚焦,如若是,则选用数据。假设接到的数量长度为0,也许产生WSAECONNRESET错误,则意味顾客端套接字主动关闭,那时急需将服务器中对应的套接字所绑定的财富自由掉,然后调解我们的套接字数组(将数组中最后二个套接字挪到近些日子的职位上)

除外部要求要有规范化选拔顾客端的连续几日外,还须要在三回九转数为0的情形下做特别管理,因为借使读集中未有其余套接字,select函数会马上回到,那将导致工小编线程成为多个毫不停顿的死循环,CPU的占用率马上达到100%。

二.异步选用
Winsock提供了一个有效的异步I/O模型。利用那些模型,应用程序可在一个套接字上,选择以Windows新闻为功底的互联网事件通报。具体的做法是在建好三个套接字后,调用WSAAsyncSelect函数。该模型最先现身于Winsock的1.1版本中,用于帮忙应用程序开垦者面向一些最先的14人Windows平台(如Windows for Workgroups),适应其“落后”的多义务新闻遭逢。应用程序仍可从这种模型中拿走好处,特别是它们用叁个正规的Windows例程(常称为"WndProc"),对窗口语资讯息实行田间管理的时候。该模型亦获得了Microsoft Foundation Class(微软基本类,MFC)对象CSocket的选择。(节选自《Windows网络编制程序》第八章卡塔尔
自己要么先贴出代码,然后做详整:
#include <winsock.h>
#include <tchar.h>

#define PORT      5150
#define MSGSIZE   1024
#define WM_SOCKET WM_USER+0

#pragma comment(lib, "ws2_32.lib")

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
  static TCHAR szAppName[] = _T("AsyncSelect Model");
  HWND         hwnd ;
  MSG          msg ;
  WNDCLASS     wndclass ;

  wndclass.style         = CS_HREDRAW | CS_VREDRAW ;
  wndclass.lpfnWndProc   = WndProc ;
  wndclass.cbClsExtra    = 0 ;
  wndclass.cbWndExtra    = 0 ;
  wndclass.hInstance     = hInstance ;
  wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
  wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
  wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
  wndclass.lpszMenuName  = NULL ;
  wndclass.lpszClassName = szAppName ;

  if (!RegisterClass(&wndclass))
  {
    MessageBox (NULL, TEXT ("This program requires Windows NT!"), szAppName, MB_ICONERROR) ;
    return 0 ;
  }

  hwnd = CreateWindow (szAppName,                  // window class name
                       TEXT ("AsyncSelect Model"), // window caption
                       WS_OVERLAPPEDWINDOW,        // window style
                       CW_USEDEFAULT,              // initial x position
                       CW_USEDEFAULT,              // initial y position
                       CW_USEDEFAULT,              // initial x size
                       CW_USEDEFAULT,              // initial y size
                       NULL,                       // parent window handle
                       NULL,                       // window menu handle
                       hInstance,                  // program instance handle
                       NULL) ;                     // creation parameters

  ShowWindow(hwnd, iCmdShow);
  UpdateWindow(hwnd);

  while (GetMessage(&msg, NULL, 0, 0))
  {
    TranslateMessage(&msg) ;
    DispatchMessage(&msg) ;
  }
  
  return msg.wParam;
}

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  WSADATA       wsd;
  static SOCKET sListen;
  SOCKET        sClient;
  SOCKADDR_IN   local, client;
  int           ret, iAddrSize = sizeof(client);
  char          szMessage[MSGSIZE];

  switch (message)
  {
 case WM_CREATE:
    // Initialize Windows Socket library
  WSAStartup(0x0202, &wsd);
  
  // Create listening socket
    sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
  // Bind
    local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
  local.sin_family = AF_INET;
  local.sin_port = htons(PORT);
  bind(sListen, (struct sockaddr *)&local, sizeof(local));
  
  // Listen
    listen(sListen, 3);

    // Associate listening socket with FD_ACCEPT event
  WSAAsyncSelect(sListen, hwnd, WM_SOCKET, FD_ACCEPT);
  return 0;

  case WM_DESTROY:
    closesocket(sListen);
    WSACleanup();
    PostQuitMessage(0);
    return 0;
  
  case WM_SOCKET:
    if (WSAGETSELECTERROR(lParam))
    {
      closesocket(wParam);
      break;
    }
    
    switch (WSAGETSELECTEVENT(lParam))
    {
    case FD_ACCEPT:
      // Accept a connection from client
      sClient = accept(wParam, (struct sockaddr *)&client, &iAddrSize);
      
      // Associate client socket with FD_READ and FD_CLOSE event
      WSAAsyncSelect(sClient, hwnd, WM_SOCKET, FD_READ | FD_CLOSE);
      break;

    case FD_READ:
      ret = recv(wParam, szMessage, MSGSIZE, 0);

      if (ret == 0 || ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET)
      {
        closesocket(wParam);
      }
      else
      {
        szMessage[ret] = '';
        send(wParam, szMessage, strlen(szMessage), 0);
      }
      break;
      
    case FD_CLOSE:
      closesocket(wParam);      
      break;
    }
    return 0;
  }
  
  return DefWindowProc(hwnd, message, wParam, lParam);
}

 以作者之见,WSAAsyncSelect是最简便的一种Winsock I/O模型(之所以说它归纳是因为一个主线程就解决了)。使用Raw Windows API写过窗口类应用程序的人应有都能看得懂。这里,我们供给做的只是是:
1.在WM_CREATE音信管理函数中,伊始化Windows Socket library,创立监听套接字,绑定,监听,况兼调用WSAAsyncSelect函数表示大家关心在监听套接字上发生的FD_ACCEPT事件;
2.自定义八个消息WM_SOCKET,一旦在大家所关怀的套接字(监听套接字和客商端套接字)上发生了某些事件,系统就能够调用WndProc而且message参数被安装为WM_SOCKET;
3.在WM_SOCKET的消息管理函数中,分别对FD_ACCEPT、FD_READ和FD_CLOSE事件进展管理;
4.在窗口销毁音信(WM_DESTROY卡塔尔的管理函数中,大家关闭监听套接字,消灭Windows Socket library

上面那张用于WSAAsyncSelect函数的网络事件类型表能够令你对各样网络事件有更领会的认知:
表1

FD_READ
应用程序想要接收有关是否可读的通知,以便读入数据
FD_WRITE
应用程序想要接收有关是否可写的通知,以便写入数据
FD_OOB
应用程序想接收是否有带外(OOB)数据抵达的通知
FD_ACCEPT
应用程序想接收与进入连接有关的通知
FD_CONNECT
应用程序想接收与一次连接或者多点join操作完成的通知
FD_CLOSE
应用程序想接收与套接字关闭有关的通知
FD_QOS
应用程序想接收套接字“服务质量”(QoS)发生更改的通知
FD_GROUP_QOS 
应用程序想接收套接字组“服务质量”发生更改的通知(现在没什么用处,为未来套接字组的使用保留)
FD_ROUTING_INTERFACE_CHANGE
应用程序想接收在指定的方向上,与路由接口发生变化的通知
FD_ADDRESS_LIST_CHANGE 
应用程序想接收针对套接字的协议家族,本地地址列表发生变化的通知

三.风浪选用
Winsock提供了另一个灵光的异步I/O模型。和WSAAsyncSelect模型肖似的是,它也允许应用程序在三个或多少个套接字上,选取以事件为底子的网络事件通报。对于表1计算的、由WSAAsyncSelect模型运用的互连网事件来讲,它们均可维持原状地移植到新模型。在用新模型开拓的应用程序中,也能采纳和拍卖全体这个事件。该模型最注重的出入在于互联网事件会投递至七个事件目的句柄,而非投递至两个窗口例程。(节选自《Windows网络编制程序》第八章卡塔尔(قطر‎
依旧让我们先看代码然后开展深入分析:
#include <winsock2.h>
#include <stdio.h>

#define PORT    5150
#define MSGSIZE 1024

#pragma comment(lib, "ws2_32.lib")

int      g_iTotalConn = 0;
SOCKET   g_CliSocketArr[MAXIMUM_WAIT_OBJECTS];
WSAEVENT g_CliEventArr[MAXIMUM_WAIT_OBJECTS];

DWORD WINAPI WorkerThread(LPVOID);
void Cleanup(int index);

int main()
{
  WSADATA     wsaData;
  SOCKET      sListen, sClient;
  SOCKADDR_IN local, client;
  DWORD       dwThreadId;
  int         iaddrSize = sizeof(SOCKADDR_IN);

  // Initialize Windows Socket library
  WSAStartup(0x0202, &wsaData);

  // Create listening socket
  sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  // Bind
  local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
 local.sin_family = AF_INET;
 local.sin_port = htons(PORT);
  bind(sListen, (struct sockaddr *)&local, sizeof(SOCKADDR_IN));

  // Listen
  listen(sListen, 3);

  // Create worker thread
  CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId);

  while (TRUE)
  {
    // Accept a connection
    sClient = accept(sListen, (struct sockaddr *)&client, &iaddrSize);
    printf("Accepted client:%s:%dn", inet_ntoa(client.sin_addr), ntohs(client.sin_port));

    // Associate socket with network event
    g_CliSocketArr[g_iTotalConn] = sClient;
    g_CliEventArr[g_iTotalConn] = WSACreateEvent();
    WSAEventSelect(g_CliSocketArr[g_iTotalConn],
                   g_CliEventArr[g_iTotalConn],
                   FD_READ | FD_CLOSE);
    g_iTotalConn++;
  }
}

DWORD WINAPI WorkerThread(LPVOID lpParam)
{
  int              ret, index;
  WSANETWORKEVENTS NetworkEvents;
  char             szMessage[MSGSIZE];

  while (TRUE)
  {
    ret = WSAWaitForMultipleEvents(g_iTotalConn, g_CliEventArr, FALSE, 1000, FALSE);
    if (ret == WSA_WAIT_FAILED || ret == WSA_WAIT_TIMEOUT)
    {
      continue;
    }

    index = ret - WSA_WAIT_EVENT_0;
    WSAEnumNetworkEvents(g_CliSocketArr[index], g_CliEventArr[index], &NetworkEvents);

    if (NetworkEvents.lNetworkEvents & FD_READ)
    {
      // Receive message from client
      ret = recv(g_CliSocketArr[index], szMessage, MSGSIZE, 0);
      if (ret == 0 || (ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET))
      {
        Cleanup(index);
      }
      else
      {
        szMessage[ret] = '';
        send(g_CliSocketArr[index], szMessage, strlen(szMessage), 0);
      }
    }

    if (NetworkEvents.lNetworkEvents & FD_CLOSE)
  {
   Cleanup(index);
  }
  }
  return 0;
}

void Cleanup(int index)
{
  closesocket(g_CliSocketArr[index]);
 WSACloseEvent(g_CliEventArr[index]);

 if (index < g_iTotalConn - 1)
 {
  g_CliSocketArr[index] = g_CliSocketArr[g_iTotalConn - 1];
  g_CliEventArr[index] = g_CliEventArr[g_iTotalConn - 1];
 }
 
 g_iTotalConn--;
}

事件选拔模型也比较轻便,实现起来亦不是太复杂,它的基本思维是将各类套接字都和一个WSAEVENT对象对应起来,并且在论及的时候钦定须求关爱的什么样网络事件。一旦在有个别套接字上爆发了我们关怀的风浪(FD_READ和FD_CLOSE),与之相关联的WSAEVENT对象被Signaled。程序定义了五个全局数组,叁个套接字数组,二个WSAEVENT对象数组,其尺寸都以MAXIMUM_WAIT_OBJECTS(64),四个数组中的元素一一对应。
相像的,这里的顺序未有设想七个难题,一是不能够无原则的调用accept,因为我们支撑的并发连接数有限。肃清措施是将套接字按MAXIMUM_WAIT_OBJECTS分组,每MAXIMUM_WAIT_OBJECTS个套接字一组,每一组分配一个劳力线程;可能采用WSAAccept替代accept,并回调自身定义的Condition Function。第4个难题是未曾对连续几天数为0的动静做非常处理,程序在连接数为0的时候CPU占用率为百分之百。

四.重叠I/O模型
Winsock2的宣布使得Socket I/O有了和文书I/O统一的接口。大家可以通过运用Win32文件操纵函数ReadFile和WriteFile来开展Socket I/O。伴随而来的,用于平时文书I/O的重叠I/O模型和成就端口模型对Socket I/O也适用了。这个模型的帮助和益处是足以到达更佳的系统天性,但是得以完成相比较复杂,里面涉及比较多的C语言技艺。举例大家在成就端口模型中会平常用到所谓的“尾随数据”。

1.用事件通报方式实现的重叠I/O模型
#include <winsock2.h>
#include <stdio.h>

#define PORT    5150
#define MSGSIZE 1024

#pragma comment(lib, "ws2_32.lib")

typedef struct
{
  WSAOVERLAPPED overlap;
  WSABUF        Buffer;
  char          szMessage[MSGSIZE];
  DWORD         NumberOfBytesRecvd;
  DWORD         Flags;
}PER_IO_OPERATION_DATA, *LPPER_IO_OPERATION_DATA;

int                     g_iTotalConn = 0;
SOCKET                  g_CliSocketArr[MAXIMUM_WAIT_OBJECTS];
WSAEVENT                g_CliEventArr[MAXIMUM_WAIT_OBJECTS];
LPPER_IO_OPERATION_DATA g_pPerIODataArr[MAXIMUM_WAIT_OBJECTS];

DWORD WINAPI WorkerThread(LPVOID);
void Cleanup(int);

int main()
{
  WSADATA     wsaData;
  SOCKET      sListen, sClient;
  SOCKADDR_IN local, client;
  DWORD       dwThreadId;
  int         iaddrSize = sizeof(SOCKADDR_IN);

  // Initialize Windows Socket library
  WSAStartup(0x0202, &wsaData);

  // Create listening socket
  sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  // Bind
  local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
 local.sin_family = AF_INET;
 local.sin_port = htons(PORT);
  bind(sListen, (struct sockaddr *)&local, sizeof(SOCKADDR_IN));

  // Listen
  listen(sListen, 3);

  // Create worker thread
  CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId);

  while (TRUE)
  {
    // Accept a connection
    sClient = accept(sListen, (struct sockaddr *)&client, &iaddrSize);
    printf("Accepted client:%s:%dn", inet_ntoa(client.sin_addr), ntohs(client.sin_port));

    g_CliSocketArr[g_iTotalConn] = sClient;
    
    // Allocate a PER_IO_OPERATION_DATA structure
    g_pPerIODataArr[g_iTotalConn] = (LPPER_IO_OPERATION_DATA)HeapAlloc(
      GetProcessHeap(),
      HEAP_ZERO_MEMORY,
      sizeof(PER_IO_OPERATION_DATA));
    g_pPerIODataArr[g_iTotalConn]->Buffer.len = MSGSIZE;
    g_pPerIODataArr[g_iTotalConn]->Buffer.buf = g_pPerIODataArr[g_iTotalConn]->szMessage;
    g_CliEventArr[g_iTotalConn] = g_pPerIODataArr[g_iTotalConn]->overlap.hEvent = WSACreateEvent();

    // Launch an asynchronous operation
    WSARecv(
      g_CliSocketArr[g_iTotalConn],
      &g_pPerIODataArr[g_iTotalConn]->Buffer,
      1,
      &g_pPerIODataArr[g_iTotalConn]->NumberOfBytesRecvd,
      &g_pPerIODataArr[g_iTotalConn]->Flags,
      &g_pPerIODataArr[g_iTotalConn]->overlap,
      NULL);
    
    g_iTotalConn++;
  }
  
  closesocket(sListen);
  WSACleanup();
  return 0;
}

DWORD WINAPI WorkerThread(LPVOID lpParam)
{
  int   ret, index;
  DWORD cbTransferred;

  while (TRUE)
  {
    ret = WSAWaitForMultipleEvents(g_iTotalConn, g_CliEventArr, FALSE, 1000, FALSE);
    if (ret == WSA_WAIT_FAILED || ret == WSA_WAIT_TIMEOUT)
    {
      continue;
    }

    index = ret - WSA_WAIT_EVENT_0;
    WSAResetEvent(g_CliEventArr[index]);

    WSAGetOverlappedResult(
      g_CliSocketArr[index],
      &g_pPerIODataArr[index]->overlap,
      &cbTransferred,
      TRUE,
      &g_pPerIODataArr[g_iTotalConn]->Flags);

    if (cbTransferred == 0)
    {
      // The connection was closed by client
      Cleanup(index);
    }
    else
    {
      // g_pPerIODataArr[index]->szMessage contains the received data
      g_pPerIODataArr[index]->szMessage[cbTransferred] = '';
      send(g_CliSocketArr[index], g_pPerIODataArr[index]->szMessage,
        cbTransferred, 0);

      // Launch another asynchronous operation
      WSARecv(
        g_CliSocketArr[index],
        &g_pPerIODataArr[index]->Buffer,
        1,
        &g_pPerIODataArr[index]->NumberOfBytesRecvd,
        &g_pPerIODataArr[index]->Flags,
        &g_pPerIODataArr[index]->overlap,
        NULL);
    }
  }

  return 0;
}

void Cleanup(int index)
{
  closesocket(g_CliSocketArr[index]);
  WSACloseEvent(g_CliEventArr[index]);
  HeapFree(GetProcessHeap(), 0, g_pPerIODataArr[index]);

  if (index < g_iTotalConn - 1)
  {
    g_CliSocketArr[index] = g_CliSocketArr[g_iTotalConn - 1];
    g_CliEventArr[index] = g_CliEventArr[g_iTotalConn - 1];
    g_pPerIODataArr[index] = g_pPerIODataArr[g_iTotalConn - 1];
  }

  g_pPerIODataArr[--g_iTotalConn] = NULL;
}

 那么些模型与上述任何模型不一样的是它选拔Winsock2提供的异步I/O函数WSARecv。在调用WSARecv时,钦定八个WSAOVE凯雷德LAPPED构造,那几个调用不是拥塞的,相当于说,它会立即回去。一旦有数量达到的时候,被钦点的WSAOVE纳瓦拉L应用程式ED构造中的hEvent被Signaled。由于上面这么些讲话
g_CliEventArr[g_iTotalConn] = g_pPerIODataArr[g_iTotalConn]->overlap.hEvent;
使得与该套接字相关联的WSAEVENT对象也被Signaled,所以WSAWaitForMultipleEvents的调用操作成功重临。大家明日应有做的正是用与调用WSARecv近似的WSAOVERAV4L应用软件ED构造为参数调用WSAGetOverlappedResult,进而赢得本次I/O传送的字节数等有关新闻。在赢得选择的多寡后,把多少维持原状的发送到顾客端,然后重新激活四个WSARecv异步操作。

2.用完了例程情势达成的重叠I/O模型
#include <WINSOCK2.H>
#include <stdio.h>

#define PORT    5150
#define MSGSIZE 1024

#pragma comment(lib, "ws2_32.lib")

typedef struct
{
 WSAOVERLAPPED overlap;
 WSABUF        Buffer;
  char          szMessage[MSGSIZE];
 DWORD         NumberOfBytesRecvd;
 DWORD         Flags; 
 SOCKET        sClient;
}PER_IO_OPERATION_DATA, *LPPER_IO_OPERATION_DATA;

DWORD WINAPI WorkerThread(LPVOID);
void CALLBACK CompletionROUTINE(DWORD, DWORD, LPWSAOVERLAPPED, DWORD);

SOCKET g_sNewClientConnection;
BOOL   g_bNewConnectionArrived = FALSE;

int main()
{
  WSADATA     wsaData;
  SOCKET      sListen;
  SOCKADDR_IN local, client;
  DWORD       dwThreadId;
  int         iaddrSize = sizeof(SOCKADDR_IN);

  // Initialize Windows Socket library
  WSAStartup(0x0202, &wsaData);

  // Create listening socket
  sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  // Bind
  local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
 local.sin_family = AF_INET;
 local.sin_port = htons(PORT);
  bind(sListen, (struct sockaddr *)&local, sizeof(SOCKADDR_IN));

  // Listen
  listen(sListen, 3);

  // Create worker thread
  CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId);

  while (TRUE)
  {
    // Accept a connection
    g_sNewClientConnection = accept(sListen, (struct sockaddr *)&client, &iaddrSize);
    g_bNewConnectionArrived = TRUE;
    printf("Accepted client:%s:%dn", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
  }
}

DWORD WINAPI WorkerThread(LPVOID lpParam)
{
 LPPER_IO_OPERATION_DATA lpPerIOData = NULL;

  while (TRUE)
  {
    if (g_bNewConnectionArrived)
    {
      // Launch an asynchronous operation for new arrived connection
      lpPerIOData = (LPPER_IO_OPERATION_DATA)HeapAlloc(
        GetProcessHeap(),
        HEAP_ZERO_MEMORY,
        sizeof(PER_IO_OPERATION_DATA));
      lpPerIOData->Buffer.len = MSGSIZE;
      lpPerIOData->Buffer.buf = lpPerIOData->szMessage;
      lpPerIOData->sClient = g_sNewClientConnection;
      
      WSARecv(lpPerIOData->sClient,
        &lpPerIOData->Buffer,
        1,
        &lpPerIOData->NumberOfBytesRecvd,
        &lpPerIOData->Flags,
        &lpPerIOData->overlap,
        CompletionROUTINE);      
      
      g_葡京网投哪个正规,bNewConnectionArrived = FALSE;
    }

    SleepEx(1000, TRUE);
  }
  return 0;
}

void CALLBACK CompletionROUTINE(DWORD dwError,
                                DWORD cbTransferred,
                                LPWSAOVERLAPPED lpOverlapped,
                                DWORD dwFlags)
{
葡京正网网投,  LPPER_IO_OPERATION_DATA lpPerIOData = (LPPER_IO_OPERATION_DATA)lpOverlapped;
  
  if (dwError != 0 || cbTransferred == 0)
 {
    // Connection was closed by client
  closesocket(lpPerIOData->sClient);
  HeapFree(GetProcessHeap(), 0, lpPerIOData);
 }
  else
  {
    lpPerIOData->szMessage[cbTransferred] = '';
    send(lpPerIOData->sClient, lpPerIOData->szMessage, cbTransferred, 0);
    
    // Launch another asynchronous operation
    memset(&lpPerIOData->overlap, 0, sizeof(WSAOVERLAPPED));
    lpPerIOData->Buffer.len = MSGSIZE;
    lpPerIOData->Buffer.buf = lpPerIOData->szMessage;   

    WSARecv(lpPerIOData->sClient,
      &lpPerIOData->Buffer,
      1,
      &lpPerIOData->NumberOfBytesRecvd,
      &lpPerIOData->Flags,
      &lpPerIOData->overlap,
      CompletionROUTINE);
  }
}

用完了例程来落到实处重叠I/O比用事件通报轻易得多。在此个模型中,主线程只用不停的收受连接就能够;扶助线程判断有未有新的顾客端连接被确立,假如有,就为优异客商端套接字激活二个异步的WSARecv操作,然后调用SleepEx使线程处于一种可警报的守候状态,以使得I/O实现后CompletionROUTINE能够被基本调用。假设协理线程不调用SleepEx,则基本在成功三次I/O操作后,无法调用达成例程(因为做到例程的运转应该和当年激活WSARecv异步操作的代码在同四个线程之内)。
完毕例程内的实现代码比较轻便,它收取接受到的数目,然后将数据维持原状的出殡

本文由葡京网投哪个正规发布于首页,转载请注明出处:TCP客户端加2个UDP端口_接收数据有问题,VC视频教程笔记葡京网投哪个正规:

关键词:

上一篇:VC的若干实用小技巧,VC6常用操作

下一篇:没有了