Linux中用C++架設基本TCP/IP server
這是在Linux中用C++以及Linux的system call
寫的一個基本的TCP/IP server
架設server的基本routine就是這樣而已
需要的時候就直接複製使用吧
下面是我寫的程式碼
程式碼解釋我哪天有空再來補(感覺是不會補了哈哈
結果的截圖我就不放了
反正就是server
好了,今天的筆記到此結束
希望有幫助未來遺忘這些的自己,以及需要的人
寫的一個基本的TCP/IP server
架設server的基本routine就是這樣而已
需要的時候就直接複製使用吧
下面是我寫的程式碼
程式碼解釋我哪天有空再來補(感覺是不會補了哈哈
//tcpserver.cpp #include <iostream> #include <string> #include <cstring> #include <sstream> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <signal.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> /*for BSD*/ struct socket_info{ int sockfd; struct sockaddr_in addr; }; int serverTCP(std::string port){ int sockfd; struct sockaddr_in serv_addr; int SERV_TCP_PORT; std::stringstream ss; /*Open a TCP socket(an Internet stream socket).*/ if((sockfd = socket(AF_INET, SOCK_STREAM, 0))<0) std::cerr << "server: can't open stream socket"; /*Bind our lacal address so that the client can send to us*/ ss.clear(); ss.str(port); ss >> SERV_TCP_PORT; bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(SERV_TCP_PORT); if(bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))<0) std::cerr << "server: can't bind local address\n"; /*listen*/ listen(sockfd,5); return sockfd; } socket_info acceptTCP(int sockfd){ struct sockaddr_in cli_addr; socklen_t clilen; socket_info client_info; clilen = sizeof(cli_addr); client_info.sockfd = accept(sockfd, (struct sockaddr*) &cli_addr, &clilen); client_info.addr = cli_addr; return client_info; } void handleEachClient(int sockfd){ dup2(sockfd,STDIN_FILENO); dup2(sockfd,STDOUT_FILENO); std::string str_read = ""; while(1){ std::getline(std::cin, str_read, '\n'); std::cout << "server echo: " << str_read << std::endl; } } int main(int argc, char *argv[]){ int sockfd, newsockfd; std::stringstream ss; std::string str_port = ""; socket_info client; /*create main tcp server socket*/ ss.clear(); ss.str(argv[1]); ss >> str_port; sockfd = serverTCP(str_port); for(;;){ client = acceptTCP(sockfd); std::cout << "newsockfd after accept = " << client.sockfd << std::endl; std::string client_ip = inet_ntoa(client.addr.sin_addr); std::cout << "client ip = " << client_ip << std::endl; int client_port = (int) ntohs(client.addr.sin_port); std::cout << "client port = " << client_port << std::endl; if(client.sockfd<0) std::cerr << "server: accept error"; signal(SIGCHLD,SIG_IGN); if(fork() == 0){ /*child process*/ signal(SIGCHLD,SIG_DFL); close(sockfd); handleEachClient(client.sockfd); exit(0); }else{ /*parent process*/ close(newsockfd); } } }
結果的截圖我就不放了
反正就是server
希望有幫助未來遺忘這些的自己,以及需要的人
留言
張貼留言