The book UNIX Network Programming comes with many small and exquisite programs. When I read this book, rewrite the code in the book according to your own understanding (most of them are on the copybook) to deepen your understanding (it's too difficult to read a book, huh, huh ). This example is successfully tested on ubuntu10.04.
PS: The program uses the declaration of the wrap function (the first character is an upper-case function) and constant (all letters are uppercase constants). In the my_unp.h file, it is defined in unp_base.c and unp_thread.c, address: http://blog.csdn.net/aaa20090987/article/details/8096701
Program Description: this client is used to test the TCP server. The principle is very simple. Using the TCP protocol, we first establish a connection with the specified server, then read a string from the terminal, send it to the server, and finally read the server's return and display it on the terminal.
Code:
# Include "my_unp.h" Void str_cli (File * FP, int sockfd) {char sendline [maxline], recvline [maxline]; int Len; // obtain a line of string from the terminal, write it into the socket // then write it into the terminal while (fgets (sendline, maxline, FP) from the socket line string )! = NULL) {writen (sockfd, sendline, strlen (sendline); Len = read (sockfd, recvline, maxline); If (LEN = 0) error_quit ("str_cli: server terminated prematurely "); recvline [Len] = 0; fputs (recvline, stdout) ;}} int main (INT argc, char ** argv) {int sockfd; struct sockaddr_in servaddr; If (argc! = 2) error_quit ("Usage: client <IPaddress>"); // create socket sockfd = socket (af_inet, sock_stream, 0) for TCP protocol; memset (& servaddr, 0, sizeof (servaddr); servaddr. sin_family = af_inet; servaddr. sin_port = htons (serv_port); // converts program parameter 1 (argv [1]) to socket address structure inet_ton (af_inet, argv [1], & servaddr. sin_addr); // initiate a connection to the server. After the connection is successful, client_socket represents a socket connection (sockfd, (Sa *) & servaddr, sizeof (servaddr); str_cli (stdin, sockfd); Return 0 ;}
Running example (in red) (assume that the server of a bounce string has been started)
Qch @ Ubuntu :~ /Code $ GCC my_unp_v1.c client. C-O client
Qch @ Ubuntu :~ /Code $./client 127.0.0.1
ABCD
ABCD
CTRL + d