classTcpServer { private: int m_socklen; // 结构体struct sockaddr_in的大小。 structsockaddr_in m_clientaddr{}; // address of client structsockaddr_in m_serveraddr{}; // address of server public: int m_listenfd; // 监听socket int m_connfd; // 客户端连接socket bool m_btimeout; // 是否超时, true: timeout false: not time out int m_buflen{}; // 调用Read方法后,接收到的报文的大小,单位:字节。
// // Created by roccoshi on 3/24/21. // #include"TcpUtil.h"
// 输入端口argv[1] intmain(int argc, char *argv[]){ if (argc != 2) { printf("please input the ip and port, usage: ./server [port]"); } int port = atoi(argv[1]); TcpServer server; // 忽略子进程的信号, 避免产生僵尸进程 signal(SIGCHLD,SIG_IGN); // <wait/sys.h> if (!server.InitServer(port)) { printf("server.InitServer failed.\n"); return-1; } else { printf("The server port %d is listening...\n", port); }
// 多进程 while (true) { // waiting for client to connect while (!server.Accept()); int ipid = fork(); // 父进程只需要保留监听socket if (ipid > 0) { server.CloseClient(); continue; } else { // 子进程 // 子进程不需要监听socket server.CloseListen(); printf("client(%s) connected. The pid is: %d\n",server.GetIP(), getpid()); char str_buffer[1024]; // 接受客户端申请的超时时间 if (!server.Read(str_buffer, 0)) exit(0); int out_time = atoi(str_buffer); printf("The client asked for %ds of service..\n",atoi(str_buffer)); while (true) { memset(str_buffer,0,sizeof(str_buffer)); if (!server.Read(str_buffer, out_time)) break; printf("%d recv: %s\n", getpid(), str_buffer); memset(str_buffer,0,sizeof(str_buffer)); sprintf(str_buffer, "OK"); if (!server.Write(str_buffer)) break; } printf("the client %d disconnected.\n", getpid()); } } }