#i nclude "mtserver.h" int main(int argc, char* argv[]) { checkArgc(argc, 2); const char* ip = argv[1]; int port = atoi( argv[2] ); /* 1 declare socket*/ int listenfd, connfd; int ret; /* 2 initialize listen socket*/ mySocket(listenfd); /* 3 server address */ struct sockaddr_in servaddr; initSockAddr(servaddr, ip, port); /* 4 bind */ myBind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); /* 5 listen */ myListen(listenfd, 5); /* handle SIGCHLD signal*/ signal(SIGCHLD, handle_sigchild); /* 6 waiting for connecting */ pid_t chipid; socklen_t clilen; struct sockaddr_in cliaddr; for(;;) { clilen = sizeof(cliaddr); std::cout << "Waiting for connecting ..." << std::endl; connfd = myAccept(listenfd, (struct sockaddr*)&cliaddr, &clilen); printf("Connection %d established...\n", listenfd); if ( (chipid=fork()) == 0 ) { handle_recv(connfd); } } }
void handle_recv(int connfd) { char recvbuf[BUFSIZE]; while(1) { memset( recvbuf, ‘\0‘, BUFSIZE ); if ( recv(connfd, recvbuf,BUFSIZE,0) != 0) { if (!strcmp(recvbuf, "exit")) break; fprintf(stderr,"recv msg: %s\n", recvbuf); send(connfd, recvbuf, strlen(recvbuf), 0); fprintf(stderr,"send back: %s\n\n", recvbuf); } } close(connfd); exit(0); } void handle_sigchild(int signo) { pid_t pid; int stat; while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0 ) { fprintf(stderr, "child %d terminated\n", pid); return; } }
#include "mtclient.h" int main(int argc, char* argv[]) { if (argc <=2 ) { std::cout << "server ip and port needed." << std::endl; return 1; } int port = atoi(argv[2]); char* ip = argv[1]; int sockfd; struct sockaddr_in servaddr; mySocket(sockfd); initSockAddr(servaddr,ip, port); myConnect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); handle_msg(sockfd); exit(0); }
void handle_msg(int sockfd) { char sendbuf[BUFSIZE]; char recvbuf[BUFSIZE]; while(1) { memset( sendbuf, ‘\0‘, BUFSIZE ); memset( recvbuf, ‘\0‘, BUFSIZE ); printf("%s", "send msg:"); gets(sendbuf); if (strlen(sendbuf) > 0) send(sockfd,sendbuf,strlen(sendbuf),0); if ( !strcmp(sendbuf, "exit")) break; recv(sockfd,recvbuf,BUFSIZE,0); printf("recv back:%s\n\n", recvbuf); } close( sockfd ); return; }
#include <signal.h> _sighandler_t signal ( int sig, _sighandler_t _handler );
for( ; ; ) { chilen = sizeof(cliaddr); if ( (connfd = accept(listenfd, (struct sockaddr* ) &cliaddr, &clilen )) < 0 ) { if (errno == EINTR) // 检测到错误类型为EINTR时,重启accept系统调用 continue; else err_sys ("accept error"); } }
#include <sys/wait.h> pid_t wait( int *statloc ); pid_t waitpid(pid_t pid, int *statloc, int options);
void sig_child(int signo) { pid_t pid; int stat; while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0 ) printf("Child %d terminated\n", pid); return; }
服务器编程入门(10)TCP回射服务器实现 - 并发,布布扣,bubuko.com
原文:http://blog.csdn.net/zs634134578/article/details/22305787