套接字,从外部域获取空响应

时间:2012-02-21 19:34:33

标签: c linux sockets

我有这个代码,简单的套接字C示例代码,它适用于我在本地计算机上编写并运行的简单servidor,但是如果我尝试例如从谷歌网页获取html,它会显着延迟时间回复并返回空缓冲区。

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <errno.h>


void bye(char * mmo);

void bye(char * mm) {
    printf("%s\n", mm);
    exit(0);
}

int main(void) {

    int tcpSocket, port;
    char buffer[256],err[256], *servername,* mm;

    struct hostent *server;
   struct sockaddr_in serverAddr;

    servername = "google.com";
    tcpSocket = socket(AF_INET, SOCK_STREAM, 0);
    port = 80;

    server = gethostbyname(servername);
    mm = "baa";

    if(tcpSocket < 0) {
        sprintf(err, "Can't to initialize TCP socket communication(%s).",   strerror(errno));
        bye(err);
    }   

    if(NULL == server) {
        bye("Server not found");
    }

     memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    memcpy(&serverAddr.sin_addr.s_addr,
              server->h_addr, 
           server->h_length);
   serverAddr.sin_port = htons(port);

    if(connect(tcpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
        sprintf(err, "failed internet connection. %s", strerror(errno));
        bye(err);
    }
    if(write(tcpSocket, mm, strlen(mm)) < 0) {
        sprintf(err, "Can't send.(%s)\n", strerror(errno));
        bye(err);
    } 

    memset(buffer, 0, sizeof(buffer));

    while(read(tcpSocket, buffer, 255) < 0) {
            printf("%s", buffer);
    }

    close(tcpSocket);
    printf("done!\n");

    return 0;
}

提前致谢。)

1 个答案:

答案 0 :(得分:0)

参考读取结果的代码:

while(read(tcpSocket, buffer, 255) < 0) {
        printf("%s", buffer);
}

这样的代码只打印出缓冲区的内容,以防read()返回小于0的值,如果出错则读取该值。

您可能希望修改代码:

{
  size_t sizeReadTotal = 0;
  size_t sizeToRead = 255;
  ssize_t ssizeRead = 0;
  while (sizeToRead && (ssizeRead = read(tcpSocket, buffer + sizeReadTotal, sizeToRead))) {
    if (0 > sizeRead) {
      if (EAGAIN == errno || EWOULDBLOCK == errno)
        continue;
      else
        break;
    }

    sizeToRead -= ssizeRead;
    sizeReadTotal += ssizeRead;
  }

  if (0 > ssizeRead)
    printf("read() failed after having read %dbytes: %s\n", sizeReadTotal, strerror(errno));

  printf("Data read: '%s'\n", buffer);
}

您还应该向服务器发送'\ n'(如selbie所提到的),所以更改:

mm = "baa";

mm = "baa\n";