⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 winsockclient.cpp

📁 This zip file contain tow TDI client samples.
💻 CPP
📖 第 1 页 / 共 2 页
字号:
//
//if (0!=statusSockCall)
//  {
//   printf(JAProgNm ":  Failed in getsockopt(), rc = %d\n", WSAGetLastError());
//  }

  // Fill out the server socket's address information.
  destination_sin.sin_family = AF_INET;

  // Retrieve the host information corresponding to the host name.
  if ((phostent = gethostbyname (pIPAddr)) == NULL) 
  {
    printf(JAProgNm ":  Unable to get the host name.  Error = %d\n", WSAGetLastError ());
    closesocket (ServerSock);
    return 1;
  }

  // Assign the socket IP address.
  memcpy((char FAR *)&(destination_sin.sin_addr), 
         phostent->h_addr, 
         phostent->h_length);

  // Convert to network ordering.
  destination_sin.sin_port = htons(port);

  // Establish a connection to the server socket.
  if (connect (ServerSock, 
               (PSOCKADDR) &destination_sin, 
               sizeof (destination_sin)) == SOCKET_ERROR) 
  {
    ULONG error = WSAGetLastError();
    printf(JAProgNm ":  Connecting to the server failed.  Error = %d%s\n", error, WSAECONNREFUSED==error ? " (connection refused)" : "");
    closesocket (ServerSock);
    return 1;
  }

  // Behavior:  1) send loop.
  //            2) receive loop.

  // Send strings to the server.

  for (                                               // Add size of strings (including terminator), except for first.
       i = 1,
         ulTotalSend = 0;
       i < arraysize(pServerBoundMessage);
       i ++
      )
    ulTotalSend += strlen(pServerBoundMessage[i])+1;  

  // Send strings to the server.
  for (                                               // Send loop.
       i = 0;
       i < arraysize(pServerBoundMessage);
       i ++
      )
    {
     char * pBuffer;

     ULONG sendLn = strlen(pServerBoundMessage[i])+1; // Get size of current string, including terminator.

     if (0==i)                                        // First send?
       {
        sendLn += sizeof(ULONG)            +          // Add size of length field,
                  strlen(PgmCompiledInfo)  +          //   size of date/time compiled and
                  2;                                  //   size of closing parenthesis and period

        pBuffer = (char *)malloc(sendLn);             // Get a buffer.

        if (NULL==pBuffer)                            // No good?
          {
           printf(JAProgNm ":  Couldn't allocate buffer, quitting\n");
           goto DoShutdown;
          }

        ulTotalSend += sendLn;                        // Add size of first string.

        *(PULONG)pBuffer = ulTotalSend;               // Copy total amount to be sent.
        strcpy(pBuffer+sizeof(ULONG),                 // Copy fixed string.
               pServerBoundMessage[0]
              );
        strcat(pBuffer+sizeof(ULONG),                 // Append date/time compiled.
               PgmCompiledInfo
              );
        strcat(pBuffer+sizeof(ULONG), ").");          // Append closing parenthesis and period.

//      printf(JAProgNm ":  Sending %d bytes\n  >%s<\n", sendLn, pBuffer+sizeof(ULONG));

        printf("\n" JAProgNm ":  About to send a total of %d bytes to server\n\n", ulTotalSend);
       }
     else
       pBuffer = pServerBoundMessage[i];              // Point to fixed string.

//   printf(JAProgNm ":  Sending %d bytes\n  >%s<\n",  sendLn, pServerBoundMessage[i]);

     int lclStatus = send(ServerSock,
                          pBuffer,
                          sendLn,
                          0
                         );

     if (0==i)                                        // First send?
       free(pBuffer);                                 // Free buffer.

     if (SOCKET_ERROR==lclStatus)
       {
        printf(JAProgNm ":  Sending data #%d to the server failed.  Error = %d\n", i, WSAGetLastError());
       }
     else
       {
//      printf(JAProgNm ":  Sent %d bytes to the server\n", lclStatus);
       }
    }                                                 // End 'for' Send loop.

DoShutdown:
  // Disable sending on ServerSock.
  shutdown(ServerSock, SD_SEND);

  for (;;)
  {
    // Receive data from the server socket.
    rcRecv = recv(ServerSock, szClientA, sizeof(szClientA), 0);

    // Check if there is any data received. If there is, display it.
    if (SOCKET_ERROR==rcRecv)
    {
      printf(JAProgNm ":  No data is received, recv failed.  Error = %d\n", WSAGetLastError());
      break;
    }
    else if (0==rcRecv)
    {
      printf(JAProgNm ":  Finished receiving data\n");
      break;
    }
    else
    {
      TotalRecvd += rcRecv;                           // Accumulate total received.

      #define ServerMsgArraySz 10

      // It is assumed -- but not checked -- that in each receive there is at least 1 string and
      // that the total number of strings sent across receives does not exceed ServerMsgArraySz.

      char    * pSvrMsg[ServerMsgArraySz];
      int       msgCt = 0;
      BOOLEAN   bFindNextStr = TRUE;

      // Find strings (there may be more than one in the received data).
      for (int charIdx = 0; charIdx < rcRecv; charIdx ++)
        {
         if (TRUE==bFirst)                            // First string?
           {                                                                                                                                                                                        
            charIdx += sizeof(ULONG);                 // Bump past total byte count.                                                                                                                  
            bFirst = FALSE;                           // Turn flag off.                                                                                                                                                                                   
           }                                                                                                                                                                                        
                                                                                                                   
         if (TRUE==bFindNextStr)                      // Looking for a string?
           if (0!=szClientA[charIdx])                 // Is current byte not 0?
             {
              msgCt++;                                // Bump string count.
              pSvrMsg[msgCt-1] = &szClientA[charIdx]; // Point to current string.
              bFindNextStr = FALSE;                   // Remember now not looking for a string.
             }
           else
             ;
         else                                         // Handling a string.
           if (0==szClientA[charIdx])                 // Is current byte 0?
             bFindNextStr = TRUE;                     // Remember now looking for a string.
           else
             ;
        }

      for (int msgIdx = 0; msgIdx < msgCt; msgIdx ++)
        // Display the string(s) received from the server.
        printf(JAProgNm ":  Received from server = \n  >%s<\n", pSvrMsg[msgIdx]);
    }
  }

  printf("\n" JAProgNm ":  Total received from server = %d\n", TotalRecvd);

  // Disable receiving on ServerSock.
  shutdown(ServerSock, SD_RECEIVE);

  // Close the socket.
  closesocket(ServerSock);

  WSACleanup();

ExitPoint:
  return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -