用到的函数:其他函数在我的这篇博客中https://blog.csdn.net/weixin_45393375/article/details/100806552
#include <sys/types.h>
#include <sys/socket.h>
int listen(int sockfd, int backlog);
功能:设置等待连接的最大数量
sockfd:被监听的socket描述符
backlog:等待连接的最大数量(排队的数量)
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
功能:等待sockfd连接
addr:获取连接的地址
addrlen:设置连接地址的长度
返回值:专门用于通信的描述符
编程模型
Server |
Client |
创建socket套接字 |
创建socket套接字 |
准备地址(sockadd_in,本机地址) |
准备地址(服务器地址) |
绑定(bind) |
... |
监听(listen) |
… |
等待连接(accept、fork) |
连接(connect) |
接收请求(read/recv) |
发送请求(write/send) |
响应请求(write/send) |
接收响应(read/recv) |
关闭(close) |
关闭(close) |
服务端实现多进程接收信号:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
//1.创建套接字
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(0 > sockfd)
{
perror("socket");
return -1;
}
//2. 准备地址
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);
addr.sin_addr.s_addr = inet_addr("192.168.1.210");
socklen_t len = sizeof(addr);
//3.绑定
if(bind(sockfd,(struct sockaddr*)&addr,len))
{
perror("bind");
return -1;
}
//4.监听
if(listen(sockfd,30))
{
perror("listen");
return -1;
}
while(1)
{
//5.等待连接
struct sockaddr_in addrcli = {};
int clifd = accept(sockfd,(struct sockaddr*)&addrcli,&len);
if(0 > clifd)
{
perror("accept");
return -1;
}
//6.读取消息
else if(0 == fork())//子进程接收客户端消息
{
printf("%u连接成功\n",getpid());
while(1)
{
char buf[1024] = {};
recv(clifd,buf,sizeof(buf),0);
printf("read:%s\n",buf);
if(0 == strcmp(buf,"quit"))
{
printf("%u通信结束\n",getpid());
break;
}
}
}
else //父进程回收资源
{
waitpid(-1,NULL,WNOHANG);
}
}
return 0;
}
客户端实现发消息:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
//1.创建套接字
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(0 > sockfd)
{
perror("socket");
return -1;
}
//2.创建地址
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);
addr.sin_addr.s_addr = inet_addr("192.168.1.210");
socklen_t len = sizeof(addr);
//3.连接
if(connect(sockfd,(struct sockaddr*)&addr,len))
{
perror("connect");
return -1;
}
//4.发送消息
while(1)
{
printf(">");
char buf[1024] = {};
gets(buf);
send(sockfd,buf,sizeof(buf),0);
if(0 == strcmp(buf,"quit"))
{
printf("通信结束\n");
break;
}
}
//5.关闭套接字
close(sockfd);
return 0;
}