Linux多线程实现服务端与多个客户端通信(简单易懂)
程序员文章站
2022-03-04 08:46:08
...
运行时先运行./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);
}
推荐阅读
-
C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)
-
linux网络编程之用socket实现简单客户端和服务端的通信(基于TCP)
-
C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)
-
linux网络编程之用socket实现简单客户端和服务端的通信(基于UDP)
-
NIO实现的服务端与客户端之间的简单通信
-
基于go简单实现客户端与服务端通信
-
传输层使用udp实现客户端和服务端通信的小程序 (可以实现多个客户端与服务端通信)
-
NIO实现的简单的客户端与服务端通信(非阻塞)
-
Java Socket 使用多线程实现服务器与多个客户端通信
-
Java多线程与线程池实现Socket多个客户端连接服务器同时通信代码