winsocket http协议请求,为什么recv接收的数据没有按照顺序接收,而且在最后还要停顿一段时间才会断开
程序代码:
#include <stdio.h> #include "winsock2.h" //#pragma comment(lib, "ws2_32.lib") //2.0版本 int main() { // Initialize Winsock. WSADATA wsaData; int iResult = WSAStartup( MAKEWORD(2,2), &wsaData ); if ( iResult != NO_ERROR ){ printf("Error at WSAStartup()\n"); } // Create a socket. SOCKET m_socket; m_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); if ( m_socket == INVALID_SOCKET ) { printf( "Error at socket(): %ld\n", WSAGetLastError() ); WSACleanup(); return 1; } // Connect to a server. struct sockaddr_in clientService; clientService.sin_family = AF_INET; clientService.sin_addr.s_addr = inet_addr("113.106.90.157"); clientService.sin_port = htons( 80 ); if ( connect( m_socket, (SOCKADDR*) &clientService, sizeof(SOCKADDR)) == SOCKET_ERROR){ printf( "Failed to connect.\n" ); WSACleanup(); return; } // Send and receive data. int bytesSent; char sendbuf[1024]; sprintf(sendbuf,"%s","GET / HTTP/1.1\r\n"); strcat(sendbuf,"Host: www.\r\n"); strcat(sendbuf,"Content-Encoding: utf-8\r\n"); strcat(sendbuf,"User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0\r\n\r\n"); int bytesRecv = strlen(sendbuf); char recvbuf[1024]; char *precvbuf = recvbuf; bytesSent = send( m_socket, sendbuf, strlen(sendbuf), 0 ); printf( "Bytes Sent: %ld\n", bytesSent ); // bytesRecv = recv( m_socket, recvbuf, 2 , 0 ); // printf("\n %d\n",bytesRecv); while( 1 ) { bytesRecv = recv(m_socket, recvbuf,1024 , 0); printf("%s",recvbuf); // printf("\n%d\n",bytesRecv); if(bytesRecv<=0){ break; } } close(m_socket); return 0; } [local]1[/local][local]2[/local]