1

由于某些莫名其妙的原因,这个 C++ 程序在接受套接字时退出。套接字被接受,这反映在客户端,但服务器随后自发爆炸。

完整代码如下:

#include <sys/types.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include <errno.h>

#define BUF_SIZE 500
#define BACKLOG 50

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        printf("Usage %s port\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in addr;
    struct sockaddr_storage theiraddr;
    socklen_t addrlen;
    char buf[BUF_SIZE];

    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = INADDR_ANY;

    theiraddr.ss_family = AF_INET;

    int sockfd = socket(AF_INET, SOCK_STREAM|SOCK_NONBLOCK, 0);

    if (sockfd == -1)
    {
        printf("Sock Error!\n");
        exit(EXIT_FAILURE);
    }

    if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
    {
        printf("Bind Error!\n");
        exit(EXIT_FAILURE);
    }

    if (listen(sockfd, BACKLOG) == -1)
    {
        printf("Listen Error!\n");
        exit(EXIT_FAILURE);
    }

    addrlen = sizeof(theiraddr);
    int accepted;

    for ( int i = 0; ; i++ )
    {
        usleep(100000);

        errno = 0;
        printf("pre-accept\n");
        accepted = accept(sockfd, (struct sockaddr *)&theiraddr, &addrlen);
        printf("%i", accepted == -1); //this line does not get executed

        if(errno == EWOULDBLOCK)
        {
            printf("WOULDBLOCK %i\n", i);
            continue;
        }
        else if(accepted == -1)
        {
            printf("TERRIBLE TRAGEDY\n");
        }

        printf("Accepted.\n");

        char msg[] = "You have connected.";

        send(sockfd, msg, sizeof(msg), 0);

        close(accepted);

    }
    close(sockfd);
}
4

1 回答 1

2

您没有看到错误消息,因为\n格式字符串的末尾没有 a。 stdout是行缓冲的。在任何情况下都stderr用于错误输出。

你真正的错误似乎是这个

send(sockfd, msg, sizeof(msg), 0);

我猜你的意思是发送提供给你进行通信accepted的文件描述符。accept

于 2012-12-22T23:13:30.477 回答