The main function: ------------------------------------------ //server----server is a passive role 1.socket // buy a cell phone 2.bind //SIM card binds a mobile number (ip+port) 3.listen //standby (wait for phone call) 4.accept / / answer the phone 5.read/write // call 6.close //Hook up //client - client is an end that initiates a request 1.socket // buy a cell phone 2.bind (optional) //SIM card (bind number) 3.connect //make a call 4.read/write //call 5.close //Hook up //1.socket ---- socket Int socket(int domain, int type, int protocol); Function: Create a socket for communication parameter: @domain //"domain" --range AF_INET //Communication of IPV4 protocol @type SOCK_STREAM //TCP (stream socket) @Protocol 0 / / LINUX downstream socket ==>TCP //protocol return value: Corresponding socket file descriptor successfully Failed to return -1 note: File descriptors: Is actually an identifier for creating a good socket //2.bind Int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen); Features: Bind address information to the specified socket parameter: @sockfd // represents the socket for the operation @addr // Filled address information (ip + port) @addrlen //The size of the address information structure return value: Success 0 Failure -1 // Universal address structure Struct sockaddr { Sa_family_t sa_family; //AF_INET //IPV4 protocol Char sa_data[14];//(ip+port) } //Network communication address structure (internet) Struct sockaddr_in { Sa_family_t sin_family; /* address family: AF_INET */ In_port_t sin_port; /* port in network byte order */ Struct in_addr sin_addr; /* internet address */ }; /* Internet address. */ Struct in_addr { Uint32_t s_addr; /* address in network byte order */ }; //1. Define an address structure variable Struct sockaddr_in addr; Bzero(&addr,sizeof(addr)); //Clear 0 function //2. Fill information after Addr.sin_family = AF_INET; Addr.sin_port = htons(8888); Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //127.0.0.1 is the address of the loopback test //3. Binding If(bind(sockfd,(struct sockaddr*)&addr,sizeof(addr)) < 0) { Perror("bind fail"); Return 0; } //3.listen --- set listener --- role: let the operating system monitor whether the client initiates a connection Int listen(int sockfd, int backlog); Features: Set up listening parameter: @sockfd //Monitor socket @backlog //The size of the listening queue return value Success 0 Failure -1 Listenfd --------------Listener Queue ------------------ Fd1 fd2 fd3 fd4 | -|-------------------------------------- | \---->Create a connected socket The accept function gets the connected socket's return correspondence Identifier Read and write operations after |---> are passed this identifier ongoing ----------------------------------------------- Accept(); //accept retrieves the connected socket from the listener queue and returns an identifier to indicate the connected socket //The subsequent communication via the connected socket Int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); Function: Get connection parameter: @sockfd //The fd (identifier) ​​of the listening socket @addr // Caller ID (save the address of the peer) (ip+port) @addrlen //Indicates the size of the corresponding type of the addr parameter, the value of the result parameter --- is in use, must be assigned an initial value, the final function call is completed // This parameter returns a result value return value: The identifier of the successfully connected socket Failure -1 //connect --- initiate a connection Int connect ( Int sockfd, // indicates the identifier of the socket to communicate Const struct sockaddr *addr, //Address information of the peer (ip+port) Socklen_t addrlen); // indicates the length of the addr parameter type parameter: @sockfd //fd obtained by socket function @addr //server-side address @addrlen // The size of the parameter addr //Data flow to fd --> buf (count indicates how many bytes are read at a time) Ssize_t read(int fd, void *buf, size_t count); //Data flow to buf-->fd (count indicates how many bytes are written at one time) Ssize_t write(int fd, const void *buf, size_t count); parameter: @fd is the identifier corresponding to the socket to operate @buf The first address of a memory that holds data @count The number of bytes of an operation Confd Char buf[] = "hello QCXY"; Write(confd,buf,strlen(buf)); //Write data to socket //Read the data out Char rbuf[1024] = {0}; // indicates that a 1024-byte size was requested // The memory space Read(confd,rbuf,sizeof(rbuf)); //Read data //Exercise: Enable the client to send data to the server Server sends back data Client ----- server Scanf(); ---(1)----> read after printf Read <--(2)---- write Printf Cycle to do, end condition Client ends when client enters "quit" string How to determine the client reads "quit" c language "quit" == buf; (X) //Cannot write this //Comparison function of string Strcmp("quit",buf); Strncmp("quit",buf,4); Client's program: #include #include #include #include #include #include #include //./client 127.0.0.1 8888 Int main(int argc, const char *argv[]) { Int fd; Int ret = 0; Char buf[1024] = {0}; Char rbuf[1024] = {0}; // Process command line parameters //1.socket (cell phone) //2.bind (phone card) //3.connect (to make a call) // Process command line parameters If(argc != 3) { Printf("Usage: %s Return -1; } //1.socket (cell phone) Fd = socket(AF_INET,SOCK_STREAM,0); If(fd < 0) //Error handling { Perror("socket fail"); Return -1; } Printf("fd = %d",fd); //2.bind (phone card) --- bind the client's own address information // Client address information //1. Define an address structure variable Struct sockaddr_in cli_addr; Bzero(&cli_addr,sizeof(cli_addr)); //Clear 0 function //2. Fill information after Cli_addr.sin_family = AF_INET; Cli_addr.sin_port = htons(7777); Cli_addr.sin_addr.s_addr = inet_addr(argv[1]); If(bind(fd,(struct sockaddr*)&cli_addr,sizeof(cli_addr)) < 0) { Perror("bind fail"); Return -1; } // Server address information //1. Define an address structure variable Struct sockaddr_in addr; Bzero(&addr,sizeof(addr)); //Clear 0 function //2. Fill information after Addr.sin_family = AF_INET; Addr.sin_port = htons(atoi(argv[2])); Addr.sin_addr.s_addr = inet_addr(argv[1]); //3.connect (to make a call) If(connect(fd,(struct sockaddr*)&addr,sizeof(addr))<0) { Perror("connect fail"); Return -1; } Printf("connect success"); // Communication process While(1) { //The client gets data from the keyboard // Data flow to stdin --> buf Fgets(buf,sizeof(buf),stdin); //stdin means get data from the keyboard // Send to server Write(fd,buf,strlen(buf)); // Accept the server postback message Ret = read(fd,rbuf,sizeof(rbuf)); // If the postback message is //quit // end Rbuf[ret] = '\0'; Printf("rbuf = %s",rbuf); If(strncmp("quit",buf,4) == 0) { Close(fd); Break; } } Return 0; } Server #include #include #include #include #include #include //./server 127.0.0.1 8888 Int main(int argc, const char *argv[]) { Int fd = 0; Int connfd = 0; Int ret = 0; Char buf[1024] = {0}; // Process command line parameters If(argc != 3) { Printf("Usage: %s Return -1; } //1.socket create socket Fd = socket(AF_INET,SOCK_STREAM,0); If(fd < 0) //Error handling { Perror("socket fail"); Return -1; } Printf("fd = %d",fd); //2. Binding //1. Prepare address information //2. Binding // //1. Define an address structure variable Struct sockaddr_in addr; Bzero(&addr,sizeof(addr)); //Clear 0 function //2. Fill information after Addr.sin_family = AF_INET; Addr.sin_port = htons(atoi(argv[2])); Addr.sin_addr.s_addr = inet_addr(argv[1]); //127.0.0.1 is the address of the loopback test //3. Binding If(bind(fd,(struct sockaddr*)&addr,sizeof(addr)) < 0) { Perror("bind fail"); Return 0; } Printf("bind success"); //4. Setting up listening If(listen(fd,5) < 0) { Perror("listen fail"); Return -1; } Struct sockaddr_in peer_addr; Socklen_t addrlen = sizeof(peer_addr); //5. Get connected - answer the phone While(1) // can continuously accept client requests { //connfd = accept(fd,NULL,NULL); Connfd = accept(fd,(struct sockaddr*)&peer_addr,&addrlen); If(connfd < 0) { Perror("accept fail"); Return -1; } Printf("connfd = %d",connfd); Printf("-----------------------"); Printf("ip = %s",inet_ntoa(peer_addr.sin_addr)); Printf("port = %d",ntohs(peer_addr.sin_port)); Printf("-----------------------"); // Communication process / / Effect to achieve data postback While(1) { //read and write when the return value is greater than 0 means // The number of bytes successfully operated on Ret = read(connfd,buf,sizeof(buf)); //hello Buf[ret] = '\0'; //add '\0'--convert to string Printf("buf = %s",buf);//string print needs //End flag '\0' If(ret == 0 || strncmp(buf,"quit",4) == 0) { Close(connfd); Break; } Write(connfd,buf,ret); } } //telnet Return 0; } supplement: Can replace read, write with the following function Ssize_t recv(int sockfd, void* buf, size_t len, int flags); Ssize_t send(int sockfd,const void *buf,size_t len,int flags); @sockfd // The file descriptor of the socket to operate on @buf //Save the first address of the data @len // number of bytes for one operation @flags //flag 0 - default operation mode (blocking) return value: Success The number of bytes successfully manipulated Failed -1&errno Lighting And Led Connector,Led Strip Connector,Led Light Connectors,Led Strip Light Connectors Guangdong Ojun Technology Co., Ltd. , https://www.ojunconnector.com