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);
2. And why there is no create(), connect(), read(), write() methods for client
Thanks in advance
Regards,
Ewa
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 )
Quote:
newsockfd = accept(m_sockfd, (struct sockaddr*) &cli_addr, &clilen);
// This code will accept any incoming connection.
Quote:
close(m_sockfd);
It will close listening socket
Quote:
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.