目录
1.并发服务器
可以同时处理多个客户端的请求,创建子进程或者分支线程来处理客户端处理客户端的请求。
父进程/主线程只负责连接,子进程/分支线程只负责与客户端交互。
1)多进程并发服务器
代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__:", __LINE__);\
perror(msg);\
}while(0)
#define PORT 8888
#define IP "192.168.31.160" //本机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号信号,用信号的方式回收僵尸进程
sighandler_t s = signal(SIGCHLD, 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;
}
//允许端口快速重用
int reuse = 1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速重用设置成功\n");
//填充IP和端口到地址信息结构体中,实际结构体是由地址族决定:
//AF_INET --> man 7 ip
struct sockaddr_in sin;
sin.sin_family=AF_INET; //地址族必须指定为AF_INET
sin.sin_port=htons(PORT); //端口号的网络字节序:1024~49151
sin.sin_addr.s_addr=inet_addr(IP); //ubuntu的本机IP:ifconfig可以查看
//绑定服务器的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 ; //接收客户端的IP和端口
socklen_t addrlen = sizeof(cin);
int newfd;
pid_t pid;
while(1)
{
//父进程只负责连接,即只负责运行accept函数
//获取新的文件描述符,该文件描述符才是用于通信、交互的文件描述符
newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
if(newfd < 0)
{
ERR_MSG("accept");
return -1;
}
printf("[%s:%d] newfd = %d\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd);
//能运行到当前位置,则代表有客户端连接成功
//所以需要创建一个子进程用于 与客户端进行交互
pid = fork();
if(0 == pid)
{
close(sfd);
//子进程运行:只负责与客户端交互
rcv_cli_msg(newfd, cin);
//因为子进程只负责交互,当运行到当前位置时候,与客户端的交互就已经结束了
close(newfd);
exit(0);
}
else if(pid > 0)
{
//父进程运行:负责与客户端连接,newfd是用于交互的,所以newfd对于父进程来说没有用
close(newfd);
}
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)
{
fprintf(stderr, "[%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("发送成功\n");
}
return 0;
}
运行效果:
2)多线程并发服务器
代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__:", __LINE__);\
perror(msg);\
}while(0)
#define PORT 8888
#define IP "192.168.31.160"
//需要传入到线程处理函数的内容
struct msg
{
int newfd;
struct sockaddr_in cin;
};
//线程执行体
void* callBack(void* arg)
{
struct msg info = *(struct msg*)arg;
int newfd = info.newfd;
struct sockaddr_in cin = info.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)
{
fprintf(stderr, "[%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");
break;
}
printf("发送成功\n");
}
close(newfd);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建流式套接字
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
//允许端口快速重用
int reuse = 1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速重用设置成功\n");
//填充IP和端口到地址信息结构体中,实际结构体是由地址族决定:
//AF_INET --> man 7 ip
struct sockaddr_in sin;
sin.sin_family=AF_INET; //地址族必须指定为AF_INET
sin.sin_port=htons(PORT); //端口号的网络字节序:1024~49151
sin.sin_addr.s_addr=inet_addr(IP); //ubuntu的本机IP:ifconfig可以查看
//绑定服务器的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 ; //接收客户端的IP和端口
socklen_t addrlen = sizeof(cin);
int newfd;
pthread_t tid;
struct msg info; //该结构体中存储的是需要传入到线程处理函数的变量;
while(1)
{
//主线程只负责连接
//获取新的文件描述符,该文件描述符才是用于通信、交互的文件描述符
newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
if(newfd < 0)
{
ERR_MSG("accept");
return -1;
}
printf("[%s:%d] newfd = %d\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd);
info.newfd = newfd;
info.cin = cin;
//能运行到当前位置,则代表有客户端连接成功,
//则需要创建一个分支线程处理交互
if(pthread_create(&tid, NULL, callBack, (void*)&info) != 0)
{
ERR_MSG("pthread_create");
return -1;
}
//分离线程,分离后线程会自动回收自己的资源;
pthread_detach(tid);
}
close(sfd);
return 0;
}
运行结果:
注意: 进程生成的文件描述符相同,线程生成的文件描述符不同
2.域套接字
只能做本地通讯的套接字,地址族指定为AF_UNIX
1.流式域套接字(TCP)
1.1服务器
代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.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;
}
//判断要绑定的套接字文件路径是否存在
if(access("./unix", F_OK) == 0)
{
//如果存在,则需要将该套接字文件删除
if(unlink("./unix") < 0)
{
ERR_MSG("unlink");
return -1;
}
}
//填充地址信息结构体,实际结构体是由地址族决定:
struct sockaddr_un sun;
sun.sun_family=AF_UNIX;
strcpy(sun.sun_path, "./unix");
//绑定服务器的IP地址和端口,必须绑定
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_un cun ; //接收客户端的地址信息结构体
socklen_t addrlen = sizeof(cun);
//获取新的文件描述符,该文件描述符才是用于通信、交互的文件描述符
int newfd = accept(sfd, (struct sockaddr*)&cun, &addrlen);
if(newfd < 0)
{
ERR_MSG("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)
{
fprintf(stderr, "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("发送成功\n");
}
close(newfd);
close(sfd);
return 0;
}
1.2客户端
代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.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;
}
//绑定客户端自身的IP地址和端口---->非必须绑定
//填充要连接的服务器的地址信息结构体
struct sockaddr_un sun;
sun.sun_family=AF_UNIX;
strcpy(sun.sun_path, "./unix");
//连接服务器
if(connect(sfd, (struct sockaddr*)&sun, sizeof(sun)) < 0)
{
ERR_MSG("connect");
return -1;
}
printf("connect success\n");
char buf[128] = "";
ssize_t res ;
while(1)
{
bzero(buf, sizeof(buf));
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 success\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("服务器关闭\n");
break;
}
printf(":%s\n", buf);
}
close(sfd);
return 0;
}
本地终端测试:
2.报式套接字(UDP)
2.1服务器
代码:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/types.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_DGRAM,0);
if(sfd<0)
{
ERR_MSG("socket");
return -1;
}
if(access("./unix1",F_OK)==0)
{
if(unlink("./unix1")<0)
{
ERR_MSG("unlink");
return -1;
}
}
struct sockaddr_un sun;
sun.sun_family=AF_UNIX;
strcpy(sun.sun_path,"./unix1");
if(bind(sfd,(struct sockaddr*)&sun,sizeof(sun))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
char buf[128]="";
ssize_t res=0;
struct sockaddr_un cun;
socklen_t addrlen=sizeof(cun);
while(1)
{
bzero(buf,sizeof(buf));
res=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cun,&addrlen);
if(res<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.2客户端
代码:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/types.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_DGRAM,0);
if(sfd<0)
{
ERR_MSG("socket");
return -1;
}
if(access("./unix2",F_OK)==0)
{
if(unlink("./unix2")<0)
{
ERR_MSG("nulink");
return -1;
}
}
struct sockaddr_un cun;
cun.sun_family=AF_UNIX;
strcpy(cun.sun_path,"./unix2");
if(bind(sfd,(struct sockaddr*)&cun,sizeof(cun))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
struct sockaddr_un sun;
sun.sun_family=AF_UNIX;
strcpy(sun.sun_path,"./unix1");
char buf[128]="";
ssize_t res=0;
struct sockaddr_un rcv_addr;
socklen_t addrlen=sizeof(rcv_addr);
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));
res=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&rcv_addr,&addrlen);
if(res<0)
{
ERR_MSG("recvfrom");
return -1;
}
printf("[%s]:%s\n",rcv_addr.sun_path,buf);
}
close(sfd);
return 0;
}
本地终端测试: