服务端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
int main()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(0 > sockfd)
{
perror("socket");
return -1;
}
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(6666);
addr.sin_addr.s_addr = inet_addr("192.168.0.111");
socklen_t addrlen = sizeof(addr);
if(bind(sockfd,(struct sockaddr*)&addr,addrlen))
{
perror("bind");
return -1;
}
if(listen(sockfd,10))
{
perror("listen");
return -1;
}
int epfd = epoll_create(10);
struct epoll_event event;
event.data.fd = sockfd;
event.events = EPOLLIN;
epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event);
struct epoll_event* events = calloc(sizeof(struct epoll_event),10);
for(;;)
{
int cnt = epoll_wait(epfd,events,10,100000);
if(cnt <= 0) continue;
for(int i=0; i<cnt; i++)
{
printf("cnt=%d fd=%d sockfd:%d\n",cnt,events[0].data.fd,sockfd);
if(events[i].data.fd == sockfd)
{
int clifd = accept(sockfd,(struct sockaddr*)&addr,&addrlen);
if(0 > clifd) continue;
event.data.fd = clifd;
event.events = EPOLLIN;
epoll_ctl(epfd,EPOLL_CTL_ADD,clifd,&event);
}
else
{
char buf[4096] = {};
int ret = recv(events[i].data.fd,buf,sizeof(buf),0);
if(ret <= 0)
{
epoll_ctl(epfd,EPOLL_CTL_DEL,events[i].data.fd,events+i);
continue;
}
printf("clifd:%d recv:%s\n",events[i].data.fd,buf);
send(events[i].data.fd,buf,strlen(buf)+1,1);
}
}
}
}
客户端
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main()
{
printf("服务器创建socket...\n");
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(0 > sockfd)
{
perror("socket");
return -1;
}
printf("准备地址...\n");
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(7777);
addr.sin_addr.s_addr = inet_addr("192.168.0.111");
socklen_t len = sizeof(addr);
printf("绑定连接服务器...\n");
if(connect(sockfd,(struct sockaddr*)&addr,len))
{
perror("bind");
return -1;
}
for(;;)
{
char buf[1024] = {};
printf(">");
gets(buf);
write(sockfd,buf,strlen(buf)+1);
if(0 == strcmp("quit",buf))
{
printf("通信结束!\n");
break;
}
printf("read:");
read(sockfd,buf,sizeof(buf));
printf("%s\n",buf);
}
close(sockfd);
}