TCP Socket:服务器/客户端代码结构
假设我想要一个 C 程序来执行以下操作: 1. 用户将使用输入字符串运行客户端,例如“abc” 2. 服务器会获取字符串并将其大写,然后返回'ABC' 3. 客户端不会断开连接,但可以在命令行输入更多字符串来获取结果。 4. 可以同时连接多个客户端(5个以下)。
服务器的代码结构是什么样的?这是我得到的:
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**
}
}
特别是,我不知道在哪里放置 close(newsockfd) 以及在这种情况下如何使用 Accept 。
服务器现在只是继续前进。当有新的连接时,它会正确响应。但它会忽略任何想要再次发送内容的现有客户端。
因此用户可以输入第一个字符串,但用户的第二个字符串无法到达服务器。但如果我打开另一个终端,并尝试再次连接到服务器,它仍然可以工作。
多谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
子进程必须循环处理输入,并且不能返回到accept():在EOS,它必须关闭接受的套接字并退出。
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.