CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 2012
    Posts
    19

    Post Handling Multiple Connections

    Hi Guys !

    can you explain the following code because i want to handle multiple connection and want to implement in my project

    Code:
        int newsockfd, pid;             
        socklen_t clilen;               
        struct sockaddr_in cli_addr;    
       
        listen(m_sockfd, 5);
        while(1)
        {
        
            newsockfd = accept(m_sockfd, (struct sockaddr*) &cli_addr, &clilen);
            pid = fork();
                   
            if(pid == 0)
            {
                close(m_sockfd);
                p_Game = new Game();
                p_Game->Init(newsockfd);
                exit(0);
            }
            else if(pid == -1010)
            {
                close(m_sockfd);
                p_Game = new Game();
                p_Game->Init(newsockfd);
                exit(0);
            }
            else
            {
    
                close(newsockfd);
            }
        }
        return 1;
    }
    My Questions

    1. What these lines is doing
    Code:
    newsockfd = accept(m_sockfd, (struct sockaddr*) &cli_addr, &clilen);
    Code:
    close(m_sockfd);
    Code:
     close(newsockfd);
    2. And why there is no create(), connect(), read(), write() methods for client

    Thanks in advance

    Regards,

    Ewa

  2. #2
    Join Date
    Dec 2002
    Location
    St.Louis MO, USA
    Posts
    672

    Re: Handling Multiple Connections

    This code seems incomplete and missing other parts.
    In your sample its a listening socket and accepting connections, Its missing initialization parts for example (socket function to create socket and bind function etc )

    newsockfd = accept(m_sockfd, (struct sockaddr*) &cli_addr, &clilen);
    // This code will accept any incoming connection.
    close(m_sockfd);
    It will close listening socket
    close(newsockfd);
    It will close accepted socket.
    There is no need to create accepted socket because. The accept function will return accepted socket.

    Its a server socket ( listening socket ) sample so that's why there is no connect function in this code.

    Read and Write part is also missing from your sample.
    Hope it will answer your questions.
    A Person who is polite is given goodness and a person who is away from Politeness is away from Goodness.

    NAUMAAN

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured