上代码:
int main(int argc, char *argv[])
{
int res;
pthread_t p_socket[MAX_CHAN_NUM];
void *thread_result;
int ret ,stacksize; //2k
int port_num=0;
int sockfds[MAX_CHAN_NUM];
struct timeval waitd;
fd_set read_flags,write_flags;
int err;
int n;
char buf[2];
printf("process id =%d\n",getpid());
for (int i = 0; i < MAX_CHAN_NUM; i++)
{
port_num = START_PORTNUM + i;
sockfds[i] = init_tcp("192.168.0.5",port_num);
printf("socket %d inited\n",sockfds[i]);
}
printf("all sockets created!\n");
pthread_t thread_test;
res = pthread_create(&thread_test,NULL,void_func, NULL);
if (res !=0)
{
perror("Thread create fail.\n");
exit(1);
}
blnwatch_mem =true;
timeval tvstart,tvend;
memset(send_text,0,sizeof(send_text));
srand((int)time(0));
for(int i=0;i<MAX_SEND_LENS -3;i++)
{
char buf[2];
int num;
num = (int) (9.0*rand() / (RAND_MAX + 1.0));
sprintf(buf,"%d",num);
strcat(send_text,buf);
}
try
{
while (1)
{
waitd.tv_sec = 1; // Make select wait up to 1 second for data
waitd.tv_usec = 0; // and 0 milliseconds.
FD_ZERO(&read_flags); // Zero the flags ready for using
FD_ZERO(&write_flags);
for (int i = 0; i < MAX_CHAN_NUM; i++)
{
FD_SET(sockfds[i],&read_flags);
FD_SET(sockfds[i],&write_flags);
}
err=select(MAX_CHAN_NUM, &read_flags,&write_flags,
(fd_set*)0,&waitd);
if(err < 0) continue;
for (int i = 0; i < MAX_CHAN_NUM; i++)
{
if(!IsConnected(sockfds[i]))
{
printf("reconnect.\n");
sockfds[i] = init_tcp("192.168.0.5",START_PORTNUM + i);
}
if(FD_ISSET(sockfds[i], &read_flags)) { //Socket ready for reading
FD_CLR(sockfds[i], &read_flags);
n = socket_read(sockfds[i], &buff, sizeof(buff));
if(n >0)
{
printf("read ok.\n");
strncpy(send_text,buff,n);
sprintf(buf,"%d",sockfds[i]);
strncpy(send_text,buf,2);
printf("copy ok.\n");
}
else if(n == 0)
{
printf("reconnect.\n");
sockfds[i] = init_tcp("192.168.0.5",START_PORTNUM + i);
}
else
{
printf("read error.\n");
}
}
if(FD_ISSET(sockfds[i], &write_flags)) { //Socket ready for writing
FD_CLR(sockfds[i], &write_flags);
n = socket_write(sockfds[i], &send_text, sizeof(send_text));
if (n < 0)
{
printf("write error, errno %d \n",errno);
//break;
}
else
{
printf("write ok\n");
//memset(send_text,0,sizeof(send_text));
}
}
}
printf("no data\n");
memset(send_text,0,sizeof(send_text));
srand((int)time(0));
for(int i=0;i<MAX_SEND_LENS -3;i++)
{
char buf[2];
int num;
num = (int) (9.0*rand() / (RAND_MAX + 1.0));
sprintf(buf,"%d",num);
strcat(send_text,buf);
}
}
}
catch (...)
{
printf("catch error,errno %d \n",errno);
}
printf("exit while\n");
for (int i = 0; i < MAX_CHAN_NUM; i++)
{
close_tcp(sockfds[i]);
}
debug("prot ok\n");
//close_tcp(socket_fd);
} |