客户端
#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 <pthread.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.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 maxfd=socfd;
int ret=0,count=0,clifd[50];
char buf[100];
fd_set readset,fdset;
FD_ZERO(&readset);
FD_SET(socfd,&readset);
fdset=readset;
while(1)
{
readset=fdset;
ret = select(maxfd+1,&readset,NULL,NULL,NULL);
if(ret == -1)
{
perror("select");
return -1;
}
if(FD_ISSET(socfd,&readset))
{
clifd[count] = accept(socfd,(struct sockaddr *)(&cli_addr),&len);
printf("%s上线\n",clifd[count]);
FD_SET(clifd[count],&fdset);
if(clifd[count]>maxfd)
maxfd=clifd[count];
count++;
if(ret == 1)
continue;
}
for(int i=0;i<count;i++)
{
if(FD_ISSET(clifd[i],&readset))
{
memset(buf,0,100);
read(clifd[i],buf,100);
for(int j=0;j<count;j++)
{
if(j!=i)
write(clifd[j],buf,strlen(buf));
}
}
}
}
return 0;
}