Say I want a have a C program that does this:
1. User will run a client with a input string, for example, ‘abc’
2. Server will get the string and capitalize it, and then return ‘ABC’
3. Client will NOT be disconnected, but he can enter more string at command line to get the result.
4. Multiple clients (under 5) can be connected at the same time.
What’s the code structure for server look like? Here is what I got:
master_socket = socket();
bind();
listen();
while(true)
{
**int newsockfd = accept();
if (newsockfd < 0)
//server keeps coming to here
continue; //no new connection
else
{**
int pid = fork();
if (pid == -1) { /* fork() failed */
perror("fork");
exit(EXIT_FAILURE);
}
//parent
if (pid > 0)
{
close(newsockfd);
waitpid(pid, NULL, WNOHANG);
}
else
{
close(master_socket);
//receive input string
receive();
modify();
//send back string
send();
}
//close(newsockfd); **//not sure where to put**
}
}
particularly, I don’t know where to put close(newsockfd) and how to use accept in this case.
The server right now just keep going to the the continue. When there is new connection, it will respond correctly. But it will ignore any existing client who wants to send something again.
So the user is able to input the first string, but the user’s second string cannot reach the server. But if I open another terminal, and try to connect to the server again, it can still work.
Thanks a lot.
The child process must loop processing input, and it mustn’t get back to the accept(): at EOS it must close the accepted socket and exit.