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

myhead.h

#ifndef _MYHEAD.H_
#define _MYHEAD.H_


#include
#include
#include
#include
struct fasong
{
int action;
int fromid;
int toid;
char buff[20];
};
#endif



客户端:

#include
#include "myhead.h"
#include
#include
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
#include
#include "myhead.h"
#include
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;




}

你可能感兴趣的:(网络编程)