socket编程(多线程)

利用多线程实现多个客户端和一个服务端的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模型

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值