利用多线程实现多个客户端和一个服务端的CS模型
【上一篇】:多进程版本
服务端代码如下,客户端代码不变
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<netinet/in.h>
#include<pthread.h>
typedef struct info
{
int cfd;//若为-1表示可用,大于0表示已被占用
int index;
pthread_t thread;
struct sockaddr_in client;
}INFO;
INFO thInfo[1024];
void init_thInfo()
{
int i = 0;
for(i=0; i<1024; i++)
{
thInfo[i].cfd = -1;
}
}
int findIndex()
{
int i = 0;
for(i=0; i<1024; i++)
{
if(thInfo[i].cfd == -1)
{
break;
}
}
if(i == 1024)
{
return -1;
}
return i;
}
//子线程回调函数
void* thread_work(void* arg)
{
INFO *p = (INFO*)arg;
printf("idx == [%d]\n", p->index);
int n;
int cfd = p->cfd;
char buf[1024];
while(1)
{
memset(buf, 0, sizeof(buf));
n = read(cfd, buf, sizeof(buf));
if(n <= 0)
{
printf("read error or client close\n");
break;
}
printf("port == [%d]: n == [%d], buf == [%s]\n", ntohs((p->client).sin_port), n, buf);
for(int i=0; i<n; i++)
{
buf[i] = toupper(buf[i]);
}
write(cfd, buf, n);
}
close(cfd);
pthread_exit(NULL);
}
int main()
{
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if(lfd < 0)
{
perror("socket error");
return -1;
}
struct sockaddr_in serv;
bzero(&serv, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_port = htons(8888);
serv.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(lfd, (struct sockaddr*)&serv, sizeof(serv));
if(ret < 0)
{
perror("bind error");
return -1;
}
listen(lfd, 128);
init_thInfo();
int cfd;
int idx;
char ip[16];
socklen_t len;
struct sockaddr_in client;
pthread_t thread;
while(1)
{
len = sizeof(client);
bzero(&client, sizeof(client));
cfd = accept(lfd, (struct sockaddr*)&client, &len);
idx = findIndex();
if(idx == -1)
{
close(cfd);
continue;
}
//赋值
thInfo[idx].cfd = cfd;
thInfo[idx].index = idx;
memcpy(&thInfo[idx].client, &client, sizeof(client));
printf("client: ip == [%s], port == [%d]\n", inet_ntop(AF_INET, &client.sin_addr.s_addr, ip, sizeof(ip)), ntohs(client.sin_port));
printf("lfd == [%d], cfd == [%d]\n", lfd, cfd);
pthread_create(&thInfo[idx].thread, NULL, thread_work, &thInfo[idx]);
pthread_detach(thInfo[idx].thread);
}
close(lfd);
return 0;
}
【下一篇】:select模型