它的工作原理实际上是非常特定于平台的。
如果您在 linux 系统上运行,这真的不难,您只需使用“fork”生成进程的副本,如下所示:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet.h>
#include <signal.h>
#include <unistd.h>
int main()
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_Address.sin_port = htons(1234);
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
listen(server_sockfd, 5);
signal(SIGCHLD, SIG_IGN);
while(1)
{
char ch;
printf("Server Waiting\n");
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len)
// Here's where we do the forking, if you've forked already then this will be the child running, if not then your still the parent task.
if(fork() == 0)
{
// Do what ever the child needs to do with the connected client
read(client_sockfd, &ch, 1);
sleep(5); // just for show :-)
ch++;
write(client_sockfd, &ch, 1);
close(client_sockfd);
exit(0);
}
else
{
// Parent code here, close and loop for next connection
close(client_sockfd);
}
}
}
您可能需要稍微修改一下该代码
然而,在基于 Linux / Unix 的系统下,使用 fork 是在 C 语言中执行此操作的标准方法。
在 windows 下是完全不同的故事,我不太记得所有需要的代码(这些天我已经习惯了用 C# 编码)但是设置套接字几乎是一样的,除了你需要使用 'Winsock' API 以获得更好的兼容性。
您仍然可以(我相信无论如何)在 windows 下使用标准 berkley 插座,但它充满了陷阱和漏洞,对于 windows winsock,这是一个很好的起点:
http://tangentsoft.net/wskfaq/
据我所知,如果您使用 Winsock 它有一些东西可以帮助生成和多客户端,但我个人而言,我通常只是分离一个单独的线程并将套接字连接复制到该线程,然后回到循环监听我的服务器。