Linux多线程实现服务端与多个客户端通信(简单易懂)

运行时先运行./server再运行./client,可在此代码基础上实现其他功能。
server
(gcc -o server server.c -pthread)
(./server)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
//client保存客户端的socketid,可帮助实现信息转发
int client[100],num = 0;
void *fun(void *arg)
{
	int c = (int)arg;
	while(1)
	{
		char buff[128] = {0};
		if(recv(c,buff,sizeof(buff),0) <= 0)
		{
			break;
		}
		
		for(int i = 0;i < num;i++)
		{
			send(client[i],buff,strlen(buff),0);
		}
	}
	close(c);
	pthread_exit(NULL);
}
 
int main()
{
	//创建socket
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	assert(sockfd != -1);
 	//构建结构体
	struct sockaddr_in saddr,caddr;
	memset(&saddr,0,sizeof(saddr));
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(6000);
	saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
 	//绑定
	int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
	assert(res != -1);
 	//监听
	listen(sockfd,5);
	
	while(1)
	{	
		//等待连接
		int len = sizeof(caddr);
		int c = accept(sockfd,(struct sockaddr*)&caddr,&len);
		client[num++] = c;
		if(c < 0)
		{
			continue;
		}
		
		printf("accept: c = %d,ip:%s,port:%d\n",c,inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port));
		//创建线程
		pthread_t id;
		pthread_create(&id,NULL,fun,(void*)c);
		
	}
}

client.c
(gcc -o client client.c -pthread)
(./client)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
 
void *fun(void *arg)
{
	int c = (int)arg;
	while(1)
	{
		char buff[128] = {0};
		memset(buff,0,128);
		recv(c,buff,sizeof(buff),0);
		printf("receive : %s",buff);
	}
	close(c);
	pthread_exit(NULL);
}

int main()
{
	//创建socket
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	assert(sockfd != -1);
 	//构建结构体
	struct sockaddr_in saddr;
	memset(&saddr,0,sizeof(saddr));
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(6000);
	saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
 	//建立连接
	int res = connect(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
	assert(res != -1);
	while(1)
	{
		char buff[128] = {0};
		scanf("%s",buff);
		if(strncmp(buff,"end",3) == 0)
		{
			break;
		}		
		send(sockfd,buff,strlen(buff),0);
		//创建线程
		pthread_t id;
		pthread_create(&id,NULL,fun,sockfd);	
	}
	close(sockfd);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值