Winsock2 简单tcp client示例程序

3 篇文章 0 订阅
该C程序展示了如何使用Winsock库进行TCP连接,包括连接远程服务器、事件选择、接收数据和重叠发送。程序通过WSAEventSelect设置事件,并等待多个事件,如FD_CONNECT、FD_READ和FD_CLOSE。当接收到数据时,程序会读取并立即发送回数据。程序还处理了连接失败和关闭的情况。
摘要由CSDN通过智能技术生成

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

njrobin

来根Banana~

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

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

打赏作者

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

抵扣说明:

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

余额充值