Title / Description
Code #include <unistd.h> #include <fcntl.h> #include <sys/select.h> #include <errno.h> #include "Socket.h" int main(int argc, char *argv[]){ // 对 socket 进行了简单的封装,这里实际是创建了一个套接字,同时连接到 127.0.0.1:8001 Socket sock(AF_INET, SOCK_STREAM); sock.connect({"127.0.0.1", 8001}); char buffer[1024]; while(true){ timeval timeout; timeout.tv_sec = 2; timeout.tv_usec = 0; // 设置 fd_set fd_set read_fds; FD_ZERO(&read_fds); FD_SET(sock.fd(), &read_fds); FD_SET(STDIN_FILENO, &read_fds); int max_fd = sock.fd(); // 调用 select int n = select(max_fd+1, &read_fds, nullptr, nullptr, &timeout); if(n == -1){ perror("select"); exit(1); } if(n > 0){ // socket if(FD_ISSET(sock.fd(), &read_fds)){ int len = read(sock.fd(), buffer, sizeof(buffer)); write(STDOUT_FILENO, buffer, len); } // 标准输入 if(FD_ISSET(STDIN_FILENO, &read_fds)){ int len = read(STDIN_FILENO, buffer, sizeof(buffer)); write(sock.fd(), buffer, len); } }else{ printf("no input arrive after %ld sec\n", timeout.tv_sec); } } }
Author
Highlight as C C++ CSS Clojure Delphi ERb Groovy (beta) HAML HTML JSON Java JavaScript PHP Plain text Python Ruby SQL XML YAML diff code