cou*_*sto 7 c sockets tcp client-server
我目前有一个TCP服务器设置,可以接受来自客户端的连接并回显客户端输入的任何内容.如何让多个客户端连接到服务器并将其输入发送到所有客户端?
看来我应该分叉,但我不完全确定如何......
在服务器上,我应该放置一个从accept(或listen?)开始的无限循环,当有新连接时它会分叉吗?然后在子进程中,我将不得不从先前的进程关闭套接字并连接到新的进程,但我再次不确定.
关于forks和socket操作,伪代码会是什么样子?我猜:
while(1) //before connection or accept?
pid = fork()
if(pid==0)
// open socket from client
// run the rest of the code
// end process when client disconnects
else
// close socket from client
Run Code Online (Sandbox Code Playgroud)
结果伪代码如下所示:
while(1) //before listen
pid = fork; //right after accept
if(fork>0)
close sd2 ( sd2 = accept(....) )
continue
else
run the rest of the program
Run Code Online (Sandbox Code Playgroud)