socket用select实现异步通讯

HANDLE ComPort = (HANDLE)CompletionPort;
 DWORD BytesTransferred;
 //LPOVERLAPPED Overlapped;
 LPPER_HANDLE_DATA PerHandleData;
 LPPER_IO_OPERATION_DATA PerIoData;
 DWORD SendBytes,RecvBytes;
 DWORD Flags = 0;
 BOOL bT;

 while(TRUE)
 {
  //等待完成端口上SOCKET的完成
  cout<<"["<<GetCurrentProcessId()<<":"<<GetCurrentThreadId()<<"]"<<":等待完成端口上SOCKET的完成"<<endl;
  bT = GetQueuedCompletionStatus(ComPort,
   &BytesTransferred,(LPDWORD)&PerHandleData,
   (LPOVERLAPPED *)&PerIoData,INFINITE);

  //检查是否有错误产生
  if(BytesTransferred == 0 &&
   (PerIoData->OperationType == RECV_POSTED ||
   PerIoData->OperationType == SEND_POSTED))
  {
   //关闭SOCKET
   cout<<"["<<GetCurrentProcessId()<<":"<<GetCurrentThreadId()<<"]"<<PerHandleData->sock<<"SOCKET关闭"<<endl;
   closesocket(PerHandleData->sock);
   free(PerHandleData);
   free(PerIoData);
   continue;
  }

  //如果结束socket后做了其他事情,费时间,那么...要么优化其他事情,转移到其他地方去做.要么不适用IOCP.
  //Sleep(1000);

  //为请求服务
  if(PerIoData->OperationType == RECV_POSTED)
  {
   //处理
   cout<<"["<<GetCurrentProcessId()<<":"<<GetCurrentThreadId()<<"]"<<"接收处理"<<endl;
   cout<<"["<<GetCurrentProcessId()<<":"<<GetCurrentThreadId()<<"]"<<PerHandleData->sock<<" SOCKET :"<<PerIoData->Buff<<endl;
   //回应客户端
   ZeroMemory(PerIoData->Buff,24);
   //#define _CRT_SECURE_NO_WARNINGS 1
   //strcpy(PerIoData->Buff,"OK");
   strcpy_s(PerIoData->Buff,"OK");
   Flags = 0;
   ZeroMemory((LPVOID)&(PerIoData->Overlapped),sizeof(OVERLAPPED));
   PerIoData->DataBuff.len = 2;
   PerIoData->DataBuff.buf = PerIoData->Buff;
   PerIoData->OperationType = SEND_POSTED;
   WSASend(PerHandleData->sock,&(PerIoData->DataBuff),
    1,&SendBytes,0,&(PerIoData->Overlapped),NULL);
  }
  else //if(PerIoData->OperationType == SEND_POSTED)
  {
   //发送时的处理
   cout<<"["<<GetCurrentProcessId()<<":"<<setfill('0')<<setw(4)<<GetCurrentThreadId()<<"]"<<"发送处理"<<endl;
   Flags = 0;
   ZeroMemory((LPVOID)&(PerIoData->Overlapped),sizeof(OVERLAPPED));
   ZeroMemory(PerIoData->Buff,24);
   PerIoData->DataBuff.len = 24;
   PerIoData->DataBuff.buf = PerIoData->Buff;
   PerIoData->OperationType = RECV_POSTED;
   WSARecv(PerHandleData->sock,&(PerIoData->DataBuff),
    1,&RecvBytes,&Flags,&(PerIoData->Overlapped),NULL);
  }
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bclshuai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值