0

我正在尝试在 C 中为一个项目创建一个基本的客户端/服务器系统。我有这个想法的基础......我的客户端中有一个while循环无限执行,直到服务器现在发送终止信号。我正在读/写积木。我设法让第一个读/写与服务器一起工作,但之后它就不起作用了。

我很确定我在插座上做错了什么。这个想法是我希望服务器等到客户端发送另一个 write() 命令。这是我在服务器/客户端上的内容:

客户

short connected = 1;
    do
    {
            // Send initial request on first pass
            // Afterwards send the resposne we were given
            n = write(sockfd, buffer, strlen(buffer));
            if (n < 0)
                     error("Failed to send messege. Terminating.");
            printf("%s\n", buffer);
            // Any errors?
            if (strcmp(buffer, "Session key does not match. Terminating.") == 0)
                    error(buffer);

            // Get session key response
            bzero(buffer, BUFFER_LENGTH);
            n = read(sockfd, buffer, BUFFER_LENGTH);
            if (n < 0)
                    error("Could not fetch result. Terminating.");

            printf("%s\n", buffer);
            sleep(1);
    } while (connected == 1);

服务器

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
        printf("Error opening socket.\n");
        exit(0);
}

// Taken from reference
bzero((char *) &serv_addr, sizeof(serv_addr));
portNumber = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portNumber);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
        printf("ERROR on binding.\n");
        close(sockfd);
        exit(0);
}

// Add listner to socket and wait until we are given something to do
// Taken from reference
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
{
        printf("ERROR on accept.\n");
        close(sockfd);
        exit(0);
}

// Get initial session key request
bzero(buffer,BUFFER_LENGTH);
n = read(newsockfd, buffer, BUFFER_LENGTH);
if (n < 0)
{
        printf("ERROR reading from socket.\n");
        close(newsockfd);
        close(sockfd);
        exit(0);
}

// ... a bunch of processing of data

n = write(newsockfd, response, lengthOfKey + 15 + 1);
if (n < 0)
{
        printf("ERROR writing to socket.\n");
        close(newsockfd);
        close(sockfd);
        exit(0);
}

close(newsockfd);

// Get the previous key(s) now (we hope)
short connected = 1;
while (connected < 100)
{
        printf("waiting...\n");
        newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

        //... more processing
}
4

1 回答 1

0

感谢评论,我发现 read() 块将停止服务器代码,直到它通过 write() 从客户端获得某些内容。所有工作:)谢谢

于 2012-10-03T03:16:39.403 回答