我在前面一篇博客中已经讲过了客户端和服务器端通信的流程和所需要用到的系统调用
那么,这篇博客我就利用子进程实现多个客户端和服务器端通信
代码实现:
ser.c
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0);//tcp
assert(sockfd != -1);
struct sockaddr_in saddr,caddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6000);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
assert(res != -1);
listen(sockfd,5);
while(1)
{
int len = sizeof(caddr);
int c = accept(sockfd,(struct sockaddr*)&caddr,&len);
if(c < 0)
{
continue;
}
printf("accept: c = %d,ip:%s,port:%d\n",c,inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port));
pid_t pid = fork();
assert(pid != -1);
if(pid == 0)
{
close(sockfd);
while(1)
{
char buff[128] = {0};
int len = recv(c,buff,128,0);
if(len <= 0)
{
break;
}
printf("read(%d) = %s",c,buff);
send(c,"OK",2,0);
}
close(c);
}
}
}
cli.c
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0);
assert(sockfd != -1);
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6000);
//saddr.sin_addr.s_addr = inet_addr("192.168.1.120");
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int res = connect(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
assert(res != -1);
while(1)
{
printf("input :");
char buff[128] = {0};
fgets(buff,128,stdin);
if(strncmp(buff,"end",3) == 0)
{
break;
}
send(sockfd,buff,strlen(buff),0);
memset(buff,0,128);
recv(sockfd,buff,127,0);
printf("buff = %s\n",buff);
}
close(sockfd);
}
运行结果: