0

我能够创建一个套接字,将其绑定到连接,监听它并接收结果,但在这一切中我只有 1 个连接。如何在 c 中处理多个传入连接?我通过网络得到了一些东西,但不能让它工作..

请帮忙。

4

3 回答 3

3

你可以使用fork//threadssome poll框架函数。

来自谷歌的简单 fork 示例:

#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>

void doprocessing (int sock)
{
    int n;
    char buffer[256];

    bzero(buffer,256);

    n = read(sock,buffer,255);
    if (n < 0)
    {
        perror("ERROR reading from socket");
        exit(1);
    }
    printf("Here is the message: %s\n",buffer);
    n = write(sock,"I got your message",18);
    if (n < 0)
    {
        perror("ERROR writing to socket");
        exit(1);
    }
}

int main( int argc, char *argv[] )
{
    int sockfd, newsockfd, portno;
    socklen_t clilen;
    struct sockaddr_in serv_addr, cli_addr;

    /* First call to socket() function */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("ERROR opening socket");
        exit(1);
    }
    /* Initialize socket structure */
    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = 5001;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);

    /* Now bind the host address using bind() call.*/
    if (bind(sockfd, (struct sockaddr *) &serv_addr,
                          sizeof(serv_addr)) < 0)
    {
         perror("ERROR on binding");
         exit(1);
    }
    /* Now start listening for the clients, here
     * process will go in sleep mode and will wait
     * for the incoming connection
     */
    listen(sockfd,5);
    clilen = sizeof(cli_addr);
    while (1)
    {
        newsockfd = accept(sockfd,
                (struct sockaddr *) &cli_addr, &clilen);
        if (newsockfd < 0)
        {
            perror("ERROR on accept");
            exit(1);
        }
        /* Create child process */
        pid_t pid = fork();
        if (pid < 0)
        {
            perror("ERROR on fork");
            exit(1);
        }
        if (pid == 0)
        {
            /* This is the client process */
            close(sockfd);
            doprocessing(newsockfd);
            exit(0);
        }
        else
        {
            close(newsockfd);
        }
    } /* end of while */
}
于 2012-05-16T20:39:03.373 回答
2

我可以简要介绍一下它是如何工作的。

您需要设置一个系统来侦听连接,当有连接时,它会将其推送到打开的连接列表中。在它将连接存储在列表中之后,您将创建另一个侦听器。根据连接状态定期修剪您的列表。

于 2012-05-16T20:12:07.687 回答
0

你没有提到哪个操作系统,所以我假设是 Unix/Linux。

处理多个连接的最常见方法是在单独的进程中处理每个连接,例如通过fork()或使用线程。pthreads这个想法是服务器等待连接,当一个连接被接受时,使用创建一个新进程fork()或创建一个新线程来处理新连接。这是一个不错的教程,您可能想看看。

这是一个有用的pthreads 教程

于 2012-05-16T22:45:19.020 回答