客户端
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#define IP "192.168.154.14"
#define PORT 44444
int socfd;
void* Fun_W(void* arg)
{
char buf_w[100];
while(1)
{
memset(buf_w,0,100);
printf("请输入要写入的内容:\n");
scanf("%s",buf_w);
send(socfd,buf_w,strlen(buf_w),0);
}
}
void* Fun_R(void* arg)
{
char buf_r[100];
while(1)
{
memset(buf_r,0,100);
recv(socfd,buf_r,100,0);
printf("客户端:%s\n",buf_r);
}
}
int main()
{
socfd = socket(AF_INET,SOCK_STREAM,0);
int val=1;
setsockopt(socfd,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(val));
if(socfd == -1)
{
perror("socfd");
return -1;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(IP);
addr.sin_port = htons(PORT);
connect(socfd,(struct sockaddr*)(&addr),sizeof(addr));
pthread_t pt1,pt2;
pthread_create(&pt1,NULL,Fun_W,NULL);
pthread_create(&pt2,NULL,Fun_R,NULL);
pthread_join(pt1,NULL);
pthread_join(pt2,NULL);
return 0;
}
服务器
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/epoll.h>
#define IP "192.168.154.14"
#define PORT 44444
int main()
{
int socfd = socket(AF_INET,SOCK_STREAM,0);
int val=1;
setsockopt(socfd,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(val));
if(socfd == -1)
{
perror("socfd");
return -1;
}
struct sockaddr_in self;
self.sin_family=AF_INET;
self.sin_addr.s_addr=inet_addr(IP);
self.sin_port=htons(PORT);
int bd = bind(socfd,(struct sockaddr *)(&self),sizeof(self));
if(bd == -1)
{
perror("bd");
return -1;
}
listen(socfd,50);
struct sockaddr_in cli_addr;
socklen_t len = sizeof(cli_addr);
int clifd[51],ret=0,count=0;
char buf[100]={0};
int epfd = epoll_create(1);
struct epoll_event ev;
ev.events=EPOLLIN;
ev.data.fd=socfd;
epoll_ctl(epfd,EPOLL_CTL_ADD,socfd,&ev);
struct epoll_event retev[51];
while(1)
{
int ret = epoll_wait(epfd,retev,51,-1);
if(ret == -1)
{
perror("epoll_wait");
return -1;
}
for(int i=0;i<ret;i++)
{
if((retev[i].data.fd == socfd)&&(retev[i].events&EPOLLIN))
{
clifd[count] = accept(socfd,(struct sockaddr *)(&cli_addr),&len);
printf("%d客户端上线\n",clifd[count]);
ev.events=EPOLLIN;
ev.data.fd=clifd[count];
epoll_ctl(epfd,EPOLL_CTL_ADD,clifd[count],&ev);
count++;
}
else if((retev[i].data.fd != socfd)&&(retev[i].events&EPOLLIN))
{
int re = retev[i].data.fd;
memset(buf,0,100);
int a = read(re,buf,100);
for(int i=0;i<count;i++)
{
if(re!=clifd[i]&&clifd[i]>0)
write(clifd[i],buf,strlen(buf));
}
if(a == 0)
{
printf("%d客户端下线\n",re);
for(int j=0;j<count;j++)
{
if(re == clifd[j])
clifd[j]=0;
}
epoll_ctl(epfd,EPOLL_CTL_DEL,re,NULL);
}
}
}
}
return 0;
}