利用多线程编写多个客户端向服务器并发数据

myhead.h

#ifndef _MYHEAD.H_
#define _MYHEAD.H_


#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
struct fasong
{
int action;
int fromid;
int toid;
char buff[20];
};
#endif



客户端:

#include<stdio.h>
#include "myhead.h"
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
int sfd = 0;
int rest = 0;
struct sockaddr_in sock_sever = {0};
sfd = socket(AF_INET, SOCK_STREAM,0);
if (-1 == sfd)
{
perror("socket");
exit(-1);
}
printf("stocket success!\n");
   
sock_sever.sin_family = AF_INET;
sock_sever.sin_port = htons(1235);
sock_sever.sin_addr.s_addr = inet_addr(argv[1]);
int ret = connect(sfd, (struct sockaddr *)&sock_sever, sizeof(struct sockaddr));
printf("client success!\n");
char sendbuff[20] = {0};
int sendcnt = 0;
while(1)
{
printf("please input a string:\n");
scanf("%s",sendbuff);
sendcnt = send(sfd, sendbuff, sizeof(sendbuff), 0);
if (sendcnt == -1)
{
perror("send");
exit(-3);
}
else
{
printf("send to sever %d bytes, data : %s\n", sendcnt, sendbuff);
}
if (strcmp(sendbuff, "end") == 0)
{
close(sfd);
break;
}


}
return 0;
}


服务器:

#include<stdio.h>
#include <stdlib.h>
#include "myhead.h"
#include <pthread.h>
void *mypthread(void *argc);
void *mypthread(void *argc)
{
printf("123\n");
int fd = *((int *)argc);
char recvbuff[20] = {0};
int recvcnt = 0;
while (1)
{
recvcnt = recv(fd, recvbuff,sizeof(recvbuff), 0);
if (recvcnt == -1)
{
perror("recv");
exit(-5);
}
else 
{
printf("recv from client %d bytes, data : %s\n", recvcnt, recvbuff);
}

}

}


int main()
{
struct sockaddr_in sock_sever = {0};
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd == -1)
{
perror("socket");
exit(-1);
}


sock_sever.sin_family = AF_INET;


sock_sever.sin_port = htons(1235);
sock_sever.sin_addr.s_addr  = htonl(INADDR_ANY);
if (bind(sfd, (struct sockaddr*)&sock_sever, sizeof(struct sockaddr)) == -1)
{
perror("bind");
}
else 
{
printf("bind success\n");
}
int rest = listen(sfd, 10);
if (rest == -1)
{
perror("listen");
exit(-2);
}
else
{
printf("listen success\n");
}
int len = sizeof(struct sockaddr);
while(1)
{
int clientfd = accept(sfd, (struct sockaddr*)&sock_sever, &len);
if (clientfd == -1)
{
perror("accept");
exit(-3);
}
else 
{
printf("accept success\n");

}
printf("clientfd = %d\n", clientfd);
pthread_t  id1;
int ret = pthread_create(&id1, NULL, (void *)mypthread, &clientfd);
if(ret == -1)
{
perror("pthread");
exit(-4);
}
}


return 0;




}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值