服务端实现代码:
#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>
#include <pthread.h>
int flag = 0;
int clifd[500] = {};
void* start_run(void* arg)
{
int index = flag;
clifd[flag++] = *(int*)arg;
while(1)
{
char buf[1024] = {};
recv(clifd[index],buf,sizeof(buf),0);
printf("read:%s\n",buf);
for(int i = 0 ; i < flag ; i++)
{
if(0 == strcmp(buf,"quit"))
{
send(clifd[index],buf,strlen(buf)+1,0);
clifd[index] = -1;
pthread_exit(NULL);
}
else if(-1 != clifd[i])
{
send(clifd[i],buf,strlen(buf)+1,0);
}
}
}
}
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,500))
{
perror("listen");
return -1;
}
while(1)
{
//5.准备连接
struct sockaddr_in addrcli = {};
int clifd = accept(sockfd,(struct sockaddr*)&addrcli,&len);
if(0 > clifd)
{
perror("accept");
continue;
}
pthread_t pid;
pthread_create(&pid,NULL,start_run,&clifd);
pthread_detach(pid);
}
pause();
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>
#include <pthread.h>
//负责发送消息
void* start_write(void* arg)
{
int sockfd = *(int*)arg;
while(1)
{
printf(">");
char buf[1024] = {};
gets(buf);
send(sockfd,buf,strlen(buf),0);
}
}
//负责读取消息
void* start_read(void* arg)
{
int sockfd = *(int*)arg;
while(1)
{
char buf[1024] = {};
recv(sockfd,buf,sizeof(buf),0);
if(0 == strcmp(buf,"quit"))
{
char* str = "quit";
return str;
}
printf("read:%s\n",buf);
}
}
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;
}
//写线程
pthread_t pid_write;
pthread_create(&pid_write,NULL,start_write,&sockfd);
//读线程
pthread_t pid_read;
pthread_create(&pid_read,NULL,start_read,&sockfd);
void* str = NULL;
pthread_join(pid_read,&str);
if(strcmp((char*)str,"quit"))
{
perror("pthread_join");
return -1;
}
//4. 关闭套接字
close(sockfd);
return 0;
}
这里有点问题,就是当客户端异常退出:ctrl+c 时,服务器也会退出