//----------------------------------------------------------------- // mytcpsv.c : 簡易TCP/IPサーバ [echo 機能] //----------------------------------------------------------------- #include #include #include "tcp_lib.h" //----------------------------------------------------------------- void do_tcpsv(int port); //----------------------------------------------------------------- int main(int argc,char* argv[]) { int pid,port = 7; printf("\n: end of program\n\n"); // echo サーバ用プロセスの開始 if((pid = fork()) < 0){ perror("fork"); exit(1); } if(pid == 0){ do_tcpsv(port); exit(0); } else { // 終了コマンド while(getchar()!='q') ; // プロセスの強制終了 kill(pid,SIGINT); } printf("end of TCP server.\n"); return 0; } // 簡易TCPサーバ [echo 機能] void do_tcpsv(int port) { int acc,sock,sbyte; char clhost[256]; BYTE recvcom[BUFSIZ]; struct sigaction sa; void myendsv(int no) { // 終了用 if(sock > 0) TCP_close(sock); exit(0); } // シグナルハンドラの設定 memset(&sa,0,sizeof(struct sigaction)); sa.sa_handler = myendsv; if(sigaction(SIGINT,&sa,NULL) != 0){ perror("sigaction"); return; } // サーバ起動 if((acc = TCP_acc_port(port)) < 0) return; Disp_ipinfo("echo server",port); // echo サーバ sock = -1; while(1){ sock = TCP_accept(acc,clhost); if(sock < 0){ perror("accept"); continue; } // データ送受信[echo] printf("**new client: [%s]\n",clhost); while((sbyte = TCP_recv(sock,recvcom,0)) > 0){ printf("recbuf = %s[%d byte]\n",(char*)recvcom,sbyte); TCP_send(sock,recvcom,sbyte); } printf("**client disconnected.\n"); TCP_close(sock); sock = -1; } return; }