文章目录
1.半关闭shutdown
2.端口复用setsockopt
2.1 程序中遇到的问题
2.2 端口复用
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<ctype.h>
#include<arpa/inet.h>
#define SERV_PORT 6666
int main()
{
int lfd,cfd;
struct sockaddr_in serv_addr,clie_addr;
socklen_t clie_addr_len,clie_IP_len;
char buf[BUFSIZ],clie_IP[BUFSIZ];
int n,ret;
lfd = socket(AF_INET,SOCK_STREAM,0);
//端口6666复用
int opt = 1;
setsockopt(lfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
if(lfd==-1){
perror("socket error");
exit(1);
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERV_PORT);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(lfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
if(ret==-1){
perror("bind error");
exit(1);
}
ret = listen(lfd,128);
if(ret==-1){
perror("listen error");
exit(1);
}
clie_addr_len = sizeof(clie_addr);
cfd = accept(lfd,(struct sockaddr *)&clie_addr,&clie_addr_len);
if(cfd==-1){
perror("accept error");
exit(1);
}
printf("client IP:%s,client port:%d\n",
inet_ntop(AF_INET,&clie_addr.sin_addr.s_addr,clie_IP,sizeof(clie_IP)),
ntohs(clie_addr.sin_port));
while(1){
n = read(cfd,buf,sizeof(buf));
for(int i=0;i<n;i++){
buf[i] = toupper(buf[i]);
}
write(cfd,buf,n);
}
close(lfd);
close(cfd);
return 0;
}
3.多路I/O转接
3.1 什么是多路I/O转接服务器?
3.2 select
3.3 poll
3.4 epoll
3.4.1 epoll API