IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Winsock2 简单tcp client示例程序 -> 正文阅读

[网络协议]Winsock2 简单tcp client示例程序

C程序,事件接收、重叠发送

:回传接收到的数据

#undef UNICODE

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

// link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")

#define AMOUNT_TO_READ 1024

SOCKADDR_IN RemoteADDRinf;
WSAEVENT ClientNetEvent[WSA_MAXIMUM_WAIT_EVENTS];
DWORD  ClientEventTotal=0;
char recvbuf[AMOUNT_TO_READ];

int __cdecl main(int argc, char argv)
{

    WSADATA wsaData;
    int iResult;
	WSAEVENT ConnEvent;
	WSAOVERLAPPED SendOverlapped={0};
	SOCKET sock = INVALID_SOCKET;
	DWORD Index=0;
	int fConnectDone=0;
	int fConnectFlag=0;
    ClientEventTotal=0;
	WSANETWORKEVENTS NetworkEvents;
	DWORD RecvBytes=0;
    
	WSABUF sendbuf;
    DWORD SendBytes=0;
    DWORD err=0;
    DWORD Flags=0;


    //Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", WSAGetLastError());
        return 0;
    }

	SendOverlapped.hEvent = WSACreateEvent();
    if (SendOverlapped.hEvent == NULL)
		printf("WSACreateEvent failed: %d \n", WSAGetLastError());

    sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
    if (sock == INVALID_SOCKET)
        printf("WSASocket failed: %d\n", WSAGetLastError());

	RemoteADDRinf.sin_family = AF_INET;
	RemoteADDRinf.sin_addr.s_addr = inet_addr("192.168.1.7");
	RemoteADDRinf.sin_port = htons(2000);


	ClientNetEvent[ClientEventTotal]= WSACreateEvent();

	if (ClientNetEvent[ClientEventTotal] == WSA_INVALID_EVENT)
        printf("WSACreateEvent failed: %d\n", WSAGetLastError());

    iResult=WSAEventSelect(sock, ClientNetEvent[ClientEventTotal],FD_CONNECT|FD_READ|FD_CLOSE);
    if (iResult == SOCKET_ERROR)
        printf("WSAEventSelect failed: %d\n", WSAGetLastError());

     ClientEventTotal++;

    iResult=WSAConnect(sock,&RemoteADDRinf,sizeof(struct addrinfo),NULL,NULL,NULL,NULL);
    if (iResult != SOCKET_ERROR)
        printf("WSAConnect failed: %d\n", WSAGetLastError());

    else
		{
          if (WSAEWOULDBLOCK == WSAGetLastError())
	     {
		   while(!fConnectFlag)
		   {


		     Index = WSAWaitForMultipleEvents(ClientEventTotal,ClientNetEvent,FALSE,WSA_INFINITE,FALSE);

			 switch(Index)
             {
		      case WSA_WAIT_TIMEOUT:
			  {
				  printf("WSAWaitForMultipleEvents WSA_WAIT_TIMEOUT \n");
				  fConnectFlag=1;
			  }
              break;
		      case WSA_WAIT_FAILED:
			  {
                  printf("WSAWaitForMultipleEvents WSA_WAIT_FAILED \n");
				  fConnectFlag=1;

			  }
              break;
              default:

				 WSAEnumNetworkEvents(sock, ClientNetEvent[Index - WSA_WAIT_EVENT_0], &NetworkEvents);
                 WSAResetEvent(ClientNetEvent[Index - WSA_WAIT_EVENT_0]);

			     switch(NetworkEvents.lNetworkEvents)
				 {
				   case FD_CONNECT:
				   {
                    if (NetworkEvents.iErrorCode[FD_CONNECT_BIT] != 0)
						{
						  printf("connect remote service failed= %d \n",NetworkEvents.iErrorCode[FD_CONNECT_BIT]);
                          //continue;
						  fConnectFlag=1;
						}
						else
						{
				          printf("connect remote service successful \n");
	                      fConnectFlag=1;
						  fConnectDone=1;
				        }

				   }
                   break;
				   default:
				   printf("no FD_CONNECT  \n");
				   break;
				 }

		      break;

			  }
		    }
	      }

		  else
		  {
		  }
	     }

    //system("pause");

		   while(fConnectDone)
		   {

			 Index = WSAWaitForMultipleEvents(ClientEventTotal,ClientNetEvent,FALSE,0,FALSE);

			 switch(Index)
             {
		      case WSA_WAIT_TIMEOUT:
			  {
				  //printf("WSAWaitForMultipleEvents WSA_WAIT_TIMEOUT \n");
				  //fConnectDone=1;
			  }
              break;
		      case WSA_WAIT_FAILED:
			  {
                  printf("WSAWaitForMultipleEvents WSA_WAIT_FAILED \n");
				  //fConnectDone=1;
			  }
              break;
              default:

                 //printf("connect remote service Index = %d \n",Index);

				 WSAEnumNetworkEvents(sock, ClientNetEvent[Index - WSA_WAIT_EVENT_0], &NetworkEvents);
                 WSAResetEvent(ClientNetEvent[Index - WSA_WAIT_EVENT_0]);

			     switch(NetworkEvents.lNetworkEvents)
				 {
				   case FD_READ:
				   {
                    if (NetworkEvents.iErrorCode[FD_READ_BIT] != 0)
						{
						  printf("read data failed= %d \n",NetworkEvents.iErrorCode[FD_READ_BIT]);
                          //continue;
						}
						else
						{

						  iResult = recv(sock, recvbuf, AMOUNT_TO_READ, 0);
                          if(iResult>0)
						  {
						  printf("read data : %s \n",recvbuf);
						  RecvBytes=iResult;
						  //fConnectDone=0;
						  //WSASendDisconnect(sock,NULL);
						  }
					      else
						  {
						    printf("client close \n");
	                        fConnectDone=0;
						  }
				        }
				   }
                   break;

                   case FD_CLOSE:
				   {
                       if (NetworkEvents.iErrorCode[FD_CLOSE_BIT] != 0)
						{
                         printf("close failed= %d \n",NetworkEvents.iErrorCode[FD_CLOSE_BIT]);

						}

						else
						{
							printf("server close.......... \n");
							fConnectDone=0;

						}

				   }
                   break;

				   default:
				   printf("no FD_READ  \n");
				   break;
				 }

		      break;
			  }


/
        if(RecvBytes>0)
	   {

        sendbuf.len=RecvBytes;
        sendbuf.buf=recvbuf;

        iResult = WSASend(sock,&sendbuf, 1,
                     NULL, 0, &SendOverlapped, NULL);
        if ((iResult == SOCKET_ERROR) &&
            (WSA_IO_PENDING != (err = WSAGetLastError()))) {
            printf("WSASend failed with error: %d\n", err);
			RecvBytes=0;
            break;
        }

        iResult = WSAWaitForMultipleEvents(1, &SendOverlapped.hEvent, FALSE, 2000,
                                      FALSE);
        if (iResult == WSA_WAIT_FAILED) {
            printf("WSAWaitForMultipleEvents failed with error: %d\n",
                   WSAGetLastError());
				   RecvBytes=0;
            break;
        }

        iResult = WSAGetOverlappedResult(sock, &SendOverlapped, &SendBytes,
                                    FALSE, &Flags);
        if (iResult == FALSE) {
            printf("WSASend failed with error: %d\n", WSAGetLastError());
			RecvBytes=0;
            break;
        }

        printf("Wrote %d bytes\n", SendBytes);

        WSAResetEvent(SendOverlapped.hEvent);
		RecvBytes=0;
	   }


	}


    WSACloseEvent(SendOverlapped.hEvent);
    closesocket(sock);
	while(ClientEventTotal)
	{

	  WSACloseEvent(ClientNetEvent[ClientEventTotal]);
	  ClientEventTotal--;
    }
    freeaddrinfo(&RemoteADDRinf);

    WSACleanup();

    return 0;
}

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-12-02 17:07:55  更:2021-12-02 17:10:06 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 10:05:26-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码