📄 接收数据.txt
字号:
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <memory.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <time.h>
#include <fstream>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fstream>
#include <sys/uio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/queue.h>
#include <semaphore.h>
#include <pthread.h>
#include <math.h>
#include <semaphore.h>
#include <netdb.h>
#include <iostream.h>
#define MAXLINE 128
sem_t sem_Thread; /*最大线程数量*/
sem_t sem_file;
int count_thread=255;
void delay()
{
struct timeval mTimeOut; //定时的时间
mTimeOut.tv_sec = 0;
mTimeOut.tv_usec = 1;
select(0, NULL, NULL, NULL, &mTimeOut);
return;
}
ofstream outfile("dhy",ios::app);
void main(int argc,char **argv)
{
cout<<"after delau"<<endl;
int socketfd,n;
int creat_thread_counter=0;
void recvMsg(int *connectfd);
char recvline[MAXLINE+1];
struct sockaddr_in serveraddr;
sem_init(&sem_Thread,0,255);//初始值为255
sem_init(&sem_file,0,1);//初始值为255
pthread_t pid;
socketfd = socket(AF_INET,SOCK_STREAM,0);
if(socketfd<0)
{
cout<<"create socket failed!"<<endl;
return -1;
}
bzero(&(serveraddr),sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);
serveraddr.sin_port=htons(8888);
if(bind(socketfd,(struct sockaddr*)&serveraddr,sizeof(struct sockaddr)) <0)
{
cout<<"bind 错误"<<endl;
return -1;
}
listen(socketfd,15);
while(1)
{
cout<<"*************************************************************"<<endl;
cout<<count_thread<<endl;
cout<<"总共创建:"<<creat_thread_counter<<endl;
sem_wait(&sem_Thread);
//cout<<(int)sem_Thread<<endl;
int connfd = accept(socketfd,(sockaddr*)NULL,NULL);
if(connfd >0)
cout<<"已经有一个连接建立"<<endl;
//create a thread to handle the request from client
int ret=pthread_create(&pid,NULL, (void*(*)(void*))recvMsg,&connfd);
if(ret!=0)
{
//cout << "创建线程错误!"<< endl;
//create thread failed,so post the semphere sem_Thread
sem_post(&sem_Thread);
}
else{
// cout << "创建线程成功!"<< endl;
//created a thread successfully
//creat_thread_counter is the total number of thread created
creat_thread_counter++;
}
}
//end if
}
void recvMsg(int *connectfd)
{
char buf[1000];
//set buf zero
memset(buf,0,1000);
pthread_t thread_id;
thread_id=pthread_self();
pthread_detach(thread_id);
int connfd=*connectfd;
while(1)
{
int n;
//just read and send back the same thing to the client
n=read(connfd,buf,1000);
n=send(connfd,buf,strlen(buf),MSG_NOSIGNAL);
//delay();
if(n<=0)
{
//client have break the connection
cout<<"客户端断开"<<endl;
//so break this while
break;
}
}
//post the sen_thread,just add 1
sem_post(&sem_Thread);
if(close(connfd) ==0)
{
cout<<"关闭了connectfd"<<endl;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -