几个典型的服务器模型(8.15)

 

目录

1.多进程并发服务器

1)模型

2)具体代码

2.多线程并发服务器

1)模型

2)具体代码

3.TCP本地通信

1)服务器

2)客户端

4.UDP本地通信

1)服务器

2)客户端


1.多进程并发服务器

1)模型

void handler(int sig)
{
	//回收僵尸进程
	//回收成功则再回收一次,直到回收失败或者没有回收到为止
	while(waitpid(-1, NULL, WNOHANG) > 0);
}

//捕获17号信号 SIGCHLD
sighandler_t s = signal(17, handler);

sfd = socket();
bind();
listen();
while(1)
{
    newfd = accept();
    pid = fork();
    if(pid > 0)
    {
        close(newfd);
    }
    else if(0 == pid)
    {
        close(sfd);
        while(1)
        {
            recv();
            send();
        }
        close(newfd);
        exit(0);
    }
}
close(sfd);

2)具体代码

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<signal.h>



//打印错误信息的宏函数
#define ERR_MSG(msg) do{\
	fprintf(stderr,"__%d__",__LINE__);\
	perror(msg);\
}while(0)

#define PORT 6666               //1024~49151
#define IP "192.168.31.87"     //本机IP,用ifconfig查看

typedef void(*sighandler_t)(int);

int rcv_cli_msg(int newfd,struct sockaddr_in cin);

void handler(int sig)
{
	//回收僵尸进程
	while(waitpid(-1,NULL,WNOHANG)>0);
}

int main(int argc, const char *argv[])
{

	//捕获17号信号SIGCHLD
	sighandler_t s=signal(17,handler);
	if(SIG_ERR==s)
	{
		ERR_MSG("signal");
		return -1;
	}

	//创建流式套接字
	int sfd = socket(AF_INET,SOCK_STREAM,0);
	if(sfd < 0)
	{
		ERR_MSG("socket");
		return -1;

	}
	printf("create socket success\n");

	//允许端口快速重用
	int reuse =1;
	if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse)) < 0)
	{
		ERR_MSG("setsockopt");
		return -1;
	}

	//填充地址信息结构体,真实的地址信息结构体与协议族相关
	//AF_INET,所以详情请看man 7 ip
	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port   = htons(PORT);   //网络字节序的端口号
	sin.sin_addr.s_addr =   inet_addr(IP)   ;    //网络字节序的IP地址



	//将地址信息结构体绑定到套接字上
	if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
	{
		ERR_MSG("bind");
		return -1;
	}printf("bind success\n");



	//将套接字设置为被动监听状态,让内核去监听是否有客户连接
	if(listen(sfd,10)<0)
	{
		ERR_MSG("listen");
		return -1;
	}
	printf("listen success\n");

	struct sockaddr_in cin;
	socklen_t addrlen = sizeof(cin);
	//从已完成链接的队列中,取出一个客户端的信息,创建生成一个新的套接字文件描述符
	//该文件描述符才是与客户端通信的文件描述符!!

	int newfd = 0;
	pid_t pid = 0;

	while(1)
	{
		//父进程只负责连接
		newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);
		if(newfd < 0)
		{
			perror("accept");
			return -1;
		}


		//网络字节序的IP-->点分十进制 网络字节序的port -->本机字节序
		printf("[%s : %d] newfd = %d\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);

		pid = fork();
		if(pid>0)
		{
			close(newfd);
		}
		else if(0 == pid)
		{
			close(sfd);

			//子进程运行,与客户端交互
			rcv_cli_msg(newfd,cin);

			close(newfd);

			exit(0);
		}else
		{
			ERR_MSG("fork");
			return -1;
		}
	}
	close(sfd);
	return 0;
}


int rcv_cli_msg(int newfd,struct sockaddr_in cin)
{
	char buf[128]="";
	ssize_t res = 0;
	while(1)
	{
		bzero(buf,sizeof(buf));
		//循环接收
		res=recv(newfd,buf,sizeof(buf),0);
		if(res < 0)
		{
			ERR_MSG("recv");
			return -1;
		}
		else if(0 == res)
		{
			printf("[%s : %d] newfd = %d 客户端退出\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);
			break;
		}

		printf("[%s : %d] newfd = %d :%s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,buf);


		//发送数据
		strcat(buf,"*_*");
		if(send(newfd,buf,sizeof(buf),0)<0)
		{
			ERR_MSG("send");
			return -1;
		}
		printf("send message success\n");
	}   

	return 0;
}

2.多线程并发服务器

1)模型

sfd = socket();
bind();
listen();

struct msg cliInfo;
while(1)
{
	newfd = accept();
    cliInfo.newfd = newfd;
    pthread_create(&tid, NULL, callback, &cliInfo);
}

void* callBack(void* arg)
{
    pthread_detach(pthread_self());
    while(1)
    {
        recv();
        send();
    }
    close(newfd);
    pthread_exit()
}

2)具体代码

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<pthread.h>



//打印错误信息的宏函数
#define ERR_MSG(msg) do{\
	fprintf(stderr,"__%d__",__LINE__);\
	perror(msg);\
}while(0)

#define PORT 6666               //1024~49151
#define IP "192.168.31.87"     //本机IP,用ifconfig查看

struct msg
{
	int newfd;
	struct sockaddr_in cin;
};


void* rcv_cli_msg(void* arg);

int main(int argc, const char *argv[])
{

	//创建流式套接字
	int sfd = socket(AF_INET,SOCK_STREAM,0);
	if(sfd < 0)
	{
		ERR_MSG("socket");
		return -1;

	}
	printf("create socket success\n");

	//允许端口快速重用
	int reuse =1;
	if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse)) < 0)
	{
		ERR_MSG("setsockopt");
		return -1;
	}

	//填充地址信息结构体,真实的地址信息结构体与协议族相关
	//AF_INET,所以详情请看man 7 ip
	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port   = htons(PORT);   //网络字节序的端口号
	sin.sin_addr.s_addr =   inet_addr(IP)   ;    //网络字节序的IP地址



	//将地址信息结构体绑定到套接字上
	if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
	{
		ERR_MSG("bind");
		return -1;
	}printf("bind success\n");



	//将套接字设置为被动监听状态,让内核去监听是否有客户连接
	if(listen(sfd,10)<0)
	{
		ERR_MSG("listen");
		return -1;
	}
	printf("listen success\n");

	struct sockaddr_in cin;
	socklen_t addrlen = sizeof(cin);
	//从已完成链接的队列中,取出一个客户端的信息,创建生成一个新的套接字文件描述符
	//该文件描述符才是与客户端通信的文件描述符!!

	int newfd = 0;
	pthread_t tid;
	struct msg cliInfo;

	while(1)
	{
		//父进程只负责连接
		newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);
		if(newfd < 0)
		{
			perror("accept");
			return -1;
		}


		//网络字节序的IP-->点分十进制 网络字节序的port -->本机字节序
		printf("[%s : %d] newfd = %d\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);

		cliInfo.newfd = newfd;
		cliInfo.cin = cin;

		if(pthread_create(&tid,NULL,rcv_cli_msg,(void*)&cliInfo ) !=0 )
		{
			ERR_MSG("pthread_create");
			return -1;
		}

		}
	close(sfd);
	return 0;
}

void* rcv_cli_msg(void* arg)
{
	//分离分支线程
	pthread_detach(pthread_self());

	int newfd=(*(struct msg*)arg).newfd;
    struct sockaddr_in cin = (*(struct msg*)arg).cin;

	
	char buf[128]="";
	ssize_t res = 0;
	while(1)
	{
		bzero(buf,sizeof(buf));
		//循环接收
		res=recv(newfd,buf,sizeof(buf),0);
		if(res < 0)
		{
			ERR_MSG("recv");
			break;
		}
		else if(0 == res)
		{
			printf("[%s : %d] newfd = %d client 0ff-line\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);
			break;
		}

		printf("[%s : %d] newfd = %d :%s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,buf);


		//发送数据
		strcat(buf,"*_*");
		if(send(newfd,buf,sizeof(buf),0)<0)
		{
			ERR_MSG("send");
			break;
		}
		printf("send message success\n");
	}   
	close(newfd);
	pthread_exit(NULL);
}

3.TCP本地通信

1)服务器

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>
#include<sys/un.h>



//打印错误信息的宏函数
#define ERR_MSG(msg) do{\
	fprintf(stderr,"__%d__",__LINE__);\
	perror(msg);\
}while(0);



int main(int argc, const char *argv[])
{
	//创建流式套接字
	int sfd = socket(AF_UNIX,SOCK_STREAM,0);
	if(sfd < 0)
	{
		ERR_MSG("socket");
		return -1;

	}
	printf("create socket success\n");

   //判断要绑定的文件是否存在
   //如果存在,删除文件
   if(access("./unix",F_OK)==0)
   {
	   if(unlink("./unix") < 0)
	   {
		   ERR_MSG("unlink");
		   return -1;
	   }
   }

	//填充地址信息结构体,真实的地址信息结构体与协议族相关
	//AF_INET,所以详情请看man 7 unix
	struct sockaddr_un sun;
	sun.sun_family = AF_UNIX;
	strcpy(sun.sun_path,"./unix");


	//将地址信息结构体绑定到套接字上
	if(bind(sfd,(struct sockaddr*)&sun,sizeof(sun))<0)
	{
		ERR_MSG("bind");
		return -1;
	}printf("bind success\n");



	//将套接字设置为被动监听状态,让内核去监听是否有客户连接
	if(listen(sfd,10)<0)
	{
		ERR_MSG("listen");
		return -1;
	}
	printf("listen success\n");

	struct sockaddr_in cin;
	socklen_t addrlen = sizeof(cin);
	//从已完成链接的队列中,取出一个客户端的信息,创建生成一个新的套接字文件描述符
	//该文件描述符才是与客户端通信的文件描述符!!
	int newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);
	if(newfd < 0)
	{
		perror("accept");
		return -1;
	}
    printf("newfd = %d\n",newfd);

	char buf[128]="";
	ssize_t res = 0;
	while(1)
	{
		bzero(buf,sizeof(buf));
		//循环接收
		res=recv(newfd,buf,sizeof(buf),0);
		if(res < 0)
		{
			ERR_MSG("recv");
			return -1;
		}
		else if(0 == res)
		{
			printf(" newfd = %d 客户端退出\n",newfd);
			break;
		}

		printf("newfd = %d :%s\n",newfd,buf);


		//发送数据
		strcat(buf,"*_*");
		if(send(newfd,buf,sizeof(buf),0)<0)
		{
			ERR_MSG("send");
			return -1;
		}
		printf("send message success\n");
	}          


	close(sfd);
	close(newfd);

	return 0;
}

2)客户端

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#include<sys/un.h>

#define ERR_MSG(msg) do{\
	fprintf(stderr,"__%d__",__LINE__);\
	perror(msg);\
}while(0);

int main(int argc, const char *argv[])
{
	//创建流式套接字
	int sfd=socket(AF_UNIX,SOCK_STREAM,0);
	if(sfd < 0 )
	{
		ERR_MSG("socket");
		return -1;
	}
	printf("create socket success\n");

	//绑定客户端的地址信息结构体
	//填充要链接的服务器的地址信息结构体
    struct sockaddr_un sun;
	sun.sun_family 		= AF_UNIX;
	strcpy(sun.sun_path,"./unix");


	//链接服务器 connect
	if(connect(sfd,(struct sockaddr*)&sun,sizeof(sun))<0)
	{
		ERR_MSG("connect");
		return -1;
	}

	char buf[128]="";
	ssize_t res=0;
	while(1)
	{
		//发送
		printf("请输入-->");
		fgets(buf,sizeof(buf),stdin);
		buf[strlen(buf)-1]=0;

		if(send(sfd,buf,sizeof(buf),0)<0)
		{
			ERR_MSG("send");
			return -1;
		}
		printf("send sucess\n");


		//接收
		bzero(buf,sizeof(buf));
        res = recv(sfd, buf, sizeof(buf), 0);
		if(res < 0)
		{
			ERR_MSG("recv");
			return -1;
		}
		else if(0 == res)
		{
			printf("server is off-line\n");
			break;
		}
		printf("%ld : %s\n", res, buf);
	}

	close(sfd);
	return 0;
}

4.UDP本地通信

1)服务器

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/un.h>

//打印错误新的宏函数
#define ERR_MSG(msg)  do{\
	fprintf(stderr, " __%d__ ", __LINE__);\
	perror(msg);\
}while(0)


int main(int argc, const char *argv[])
{
	//创建报式套接字
	int sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
	if(sfd < 0)
	{
		ERR_MSG("socket");
		return -1;
	}

	//判断要绑定的文件是否存在
	//如果存在,则删除该文件
	if(access("./udp_unix", F_OK) == 0)     //文件存在
	{
		//删除文件
		if(unlink("./udp_unix") < 0)
		{
			ERR_MSG("unlink");
			return -1;
		}
	}


	//填充服务器的IP地址以及端口号
	struct sockaddr_un sun;
	sun.sun_family 		= AF_UNIX;
	strcpy(sun.sun_path, "udp_unix");
	

	//绑定服务器的地址信息结构体
	if(bind(sfd, (struct sockaddr*)&sun, sizeof(sun)) < 0)
	{
		ERR_MSG("bind");
		return -1;
	}
	printf("bind success\n");

	struct sockaddr_un cun; 	//存储接收到的数据包来自哪里
	socklen_t addrlen = sizeof(cun);

	char buf[128] = "";
	while(1)
	{
		bzero(buf, sizeof(buf));
		//接收
		if(recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&cun, &addrlen) < 0)
		{
			ERR_MSG("recvfrom");
			return -1;
		}
		printf("%s : %s\n", cun.sun_path, buf);

		//发送
		strcat(buf, "*_*");

		//谁发给我,我发还给谁
		if(sendto(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&cun, sizeof(cun)) < 0)
		{
			ERR_MSG("sendto");
			return -1;
		}
		printf("sendto success\n");
	}
	//关闭套接字
	close(sfd);
	return 0;
}

2)客户端

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/un.h>

//打印错误新的宏函数
#define ERR_MSG(msg)  do{\
	fprintf(stderr, " __%d__ ", __LINE__);\
	perror(msg);\
}while(0)


int main(int argc, const char *argv[])
{
	if(argc < 2)
	{
		fprintf(stderr, "请输入客户端要绑定的文件名\n");
		return -1;
	}

	//创建报式套接字
	int sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
	if(sfd < 0)
	{
		ERR_MSG("socket");
		return -1;
	}

	//判断要绑定的文件是否存在
	//如果存在,则删除该文件
	if(access(argv[1], F_OK) == 0)     //文件存在
	{
		//删除文
		if(unlink(argv[1]) < 0)
		{
			ERR_MSG("unlink");
			return -1;
        }
    }

	//填充客户端自身要绑定的地址信息
	struct sockaddr_un cun;
	cun.sun_family 		= AF_UNIX;
	strcpy(cun.sun_path, argv[1]);

	//绑定客户端自身的地址信息结构体 ---> 必须绑定
	if(bind(sfd, (struct sockaddr*)&cun, sizeof(cun) ) < 0)
	{
		ERR_MSG("bind");
		return -1;
	}
	printf("bind success\n");


	//填充服务器的IP地址以及端口号 -->因为客户端要主动发送数据包给服务器
	struct sockaddr_un sun;
	sun.sun_family 		= AF_UNIX;
	strcpy(sun.sun_path, "udp_unix");

	struct sockaddr_un rcv_addrmsg; 	//存储接收到的数据包来自哪里
	socklen_t addrlen = sizeof(rcv_addrmsg);

	char buf[128] = "";
	while(1)
	{
		bzero(buf, sizeof(buf));

		printf("请输入>>>");
		fgets(buf, sizeof(buf), stdin);
		buf[strlen(buf)-1] = 0;

		//将数据包发送给服务器,所以地址信息结构体需要填服务器的信息
		if(sendto(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&sun, sizeof(sun)) < 0)
		{
			ERR_MSG("sendto");
			return -1;
		}
		printf("sendto success\n");

		//接收
		bzero(buf, sizeof(buf));
		//接收服务器发送过来的数据包
		//if(recvfrom(sfd, buf, sizeof(buf), 0, NULL, NULL) < 0)
		if(recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&rcv_addrmsg, &addrlen) < 0)
		{
			ERR_MSG("recvfrom");
			return -1;
		}
		printf("%s:%s\n", rcv_addrmsg.sun_path , buf);

	}
	//关闭套接字
	close(sfd);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值