while / for循环的存在会导致异常执行

时间:2017-01-17 17:28:07

标签: c sockets

我制作了小型服务器和客户端程序来比较udp和tcp所用的时间。所以我做了一个while循环来发送100条消息。问题似乎是tdp客户端中存在循环导致程序在某一行之后停止执行。调试行也没有被执行。我从未见过这种行为。 我希望循环执行100次并输出这些循环所需的时间。但是输出只是    Connection to server:port 127.0.0.1:55057

/* usage: ./tcpclient host port */

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

#define BUFSIZE 1024

void error(char *msg) {
   perror(msg);
   exit(0);
}

int main(int argc, char **argv) {
    int sockfd, portno, n;
    struct sockaddr_in serveraddr;
    struct hostent *server;
    char *hostname;
    char buf[BUFSIZE];
    strcpy(buf, "hello");
    clock_t start;  int count=0;
    /* check command line arguments */
    if (argc != 3) {
        fprintf(stderr,"usage: %s <hostname> <port>\n", argv[0]);
        exit(0);
    }
    hostname = argv[1];
    portno = atoi(argv[2]);

    /* socket: create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");

    /* gethostbyname: get the server's DNS entry */
    server = gethostbyname(hostname);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host as %s\n", hostname);
        exit(0);
    }
    /* build the server's Internet address */
    bzero((char *) &serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
            (char *)&serveraddr.sin_addr.s_addr, server->h_length);
    serveraddr.sin_port = htons(portno);

    /* connect: create a connection with the server */
    if (connect(sockfd, &serveraddr, sizeof(serveraddr)) < 0)
        error("ERROR connecting");

    /* get message line from the user */

    printf("Connection to server:port %s:%d\n",inet_ntoa(serveraddr.sin_addr),htons(portno));
    printf("I never here here in presence of loop");

    start = clock();
    while(1){
        /* send the message line to the server */
        n = write(sockfd, buf, strlen(buf));
        if (n < 0)
            error("ERROR writing to socket");
        /* print the server's reply */
        n = read(sockfd, buf, BUFSIZE);
        if (n < 0)
            error("ERROR reading from socket");
        printf("Echo from server: %s", buf);
     }
    printf("Time taken: %ld ",clock()-start);
    close(sockfd);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

该行

printf("I never here here in presence of loop");

未显示,因为stdout可能line-buffered,因此在将换行符发送到stdout或刷新stdout之前,输出将不可见。< / p>

如果您将其更改为

printf("I never here here in presence of loop\n");

它可能会出现在你的输出中。