int DaemonSocket; struct sockaddr_in DaemonAddr; int BindSocket(void) { DaemonSocket = socket(AF_INET,SOCK_STREAM,0); if (DaemonSocket==-1) return 0; DaemonAddr.sin_family = AF_INET; DaemonAddr.sin_port = htons(DAEMON_PORT); if (bind(DaemonSocket,&DaemonAddr,sizeof(DaemonAddr))<0) { printf("Can not bind!\n"); return 0; } if (listen(DaemonSocket,1024)!=0) { printf("Can not listen!\n"); return 0; } return 1; }
Incoming call
要查看是否有連線進來,可用以下方式:
int incoming_call(void) { fd_set sock; struct timeval tv; int t; FD_ZERO(&sock); FD_SET(DaemonpSignal(); if (!BindSocket()) { printf("Can not bind socket!\n"); exit(1); } WriteLock(); } printf("Chess Daemon is up, have fun!\n"); now = time(NULL); dlog("----------------------------------------------\n"); dlog( "I am back! %s" "Chess Daemon comes to alive again.\n", asctime((const struct tm*)localtime(&now)) ); do { if (incoming_call()) { if (ConnectClient()) { fd_set sock; struct timeval tv; int t; char BUF[128]; char CC[2]; int n; daemon_printf("Welcome to Chinese Chess Game Center!\n"); FD_ZERO(&sock); FD_SET(ClientSocket,&sock); n = 0; do { tv.tv_sec = 60; tv.tv_usec = 0; t = select(ClientSocket+1,&sock,NULL,NULL,&tv); if (t<=0||!FD_ISSET(ClientSocket,&sock)) ; read(ClientSocket,CC,1); if (CC[0]==13||CC[0]==10||CC[0]==0) { BUF[n] = 0; dlog("%s\n",BUF); if (strncasecmp(BUF,"exit",4)==0) { close(ClientSocket); break; } n = 0; } else { BUF[n]=CC[0]; n++; } } while (1); } } } while (1); return 1; }
void main(void) { char buf[1024]; int ok; printf("Welcome to goodie service!\n"); fflush(stdout); ok=0; do { while (fgets(buf,1023,stdin)==NULL); if (strncasecmp(buf,"exit",4)==0) ok=1; printf(buf); fflush(stdout); } while (!ok); }
int getcmd(char *cmd) { int n=0; while (cmds[n]!=NULL) { if (strncasecmp(cmd,cmds[n],strlen(cmds[n]))==0) return n; n++; } return -1; }
void main(void) { char buf[1024]; int ok; printf("Welcome to goodie service!\n"); fflush(stdout); ok=0; do { while (fgets(buf,1023,stdin)==NULL); switch (getcmd(buf)) { case -1: printf("Unknown command!\n"); break; case 0: printf("How may I help you, sir?\n"); break; case 1: printf("I will say %s",&buf[3]); break; case 2: printf("How're you doing today?\n"); break; case 3: printf("Si ya, mate!\n"); ok=1; break; case 4: printf("Go ahead!\n"); ok=1; break; } fflush(stdout); } while (!ok);