- 论坛徽章:
- 0
|
回复 #10 cookis 的帖子
下面是我帮你改过后的,cpu使用率只有0.1%
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <mysql/mysql.h>
#include <signal.h>
#include <errno.h>
#include <syslog.h>
#include <time.h>
#define MAX 0
int main()
{
int opt =1;
int clifd;
int sockSrv = socket(AF_INET,SOCK_DGRAM,0);
//setsockopt(sockSrv, SOL_SOCKET, SO_REUSEADDR, (const void*)&opt, sizeof(opt));
struct sockaddr_in addrSrv;
addrSrv.sin_addr.s_addr=htonl(INADDR_ANY);//............
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(888 ;//...........
bind(sockSrv,(struct sockaddr*)&addrSrv,sizeof(addrSrv));
char recvBuf[100];
char sendBuf[100];
char tempBuf[100];
struct sockaddr_in addrClient;
int len = sizeof(struct sockaddr);
printf(".......!!!\n" ;
struct timeval tv;
while(1)
{
tv.tv_sec=1;
tv.tv_usec=0;
fd_set fdsocket;
FD_ZERO(&fdsocket);
FD_SET(sockSrv,&fdsocket);
if(select(sockSrv+1,&fdsocket,NULL,NULL,&tv))
{
if(FD_ISSET(sockSrv,&fdsocket))
{
recvfrom(sockSrv,recvBuf,100,0,(struct sockaddr*)&addrClient,(socklen_t *)&len); //......
/* if('q' == recvBuf[0])
{
sendto(sockSrv,"q",strlen("q" +1,0,(sockaddr*)&addrClient,len);
printf("Chat end!\n" ;
break;
}
sprintf(tempBuf,"%s . : %s",inet_ntoa(addrClient.sin_addr),recvBuf);
printf("%s\n",tempBuf);
printf("...:" ;
gets(sendBuf);
sendto(sockSrv,sendBuf,strlen(sendBuf)+1,0,(sockaddr*)&addrClient,len);*/
}
}
}
close(sockSrv);
return 0;
} |
|