<title>TCP/IP network programming (transcription note 1) –tcp</title> TCP/IP network programming (transcription note 1) –tcptable of Contents
- Server
- Client
- A better client-side implementation
Source: "TCP/IP network Programming"
Transcription
Both sides of the communication have their own input cache and output cache
The write function of the socket is not to transmit the data immediately, but to write to the output buffer to the input buffer at the other end.
The moment the socket's read function is called, the data is read from the input buffer
The sliding window in the TCP protocol guarantees that the data will not exceed the size of the input cache.
Write (server_sock, message, strlen (message)); Read (server_sock, message, strlen (message)); There will be problems.
Cat/proc/sys/net/ipv4/tcp_rmem //kernel read cache size Cat/proc/sys/net/ipv4/tcp_wmem //kernel write cache size
Shutdown (sock, SHUT_RD); Shutdown (sock, SHUT_WR); Shutdown (sock, Shut_rdwr);
Server
int Server_sock;int Client_sock;struct sockaddr_in server_addr;struct sockaddr_in client_addr;// SocketServer_sock = socket (af_inet, sock_stream, 0);// Bindmemset (&server_addr, 0,sizeof(SERVER_ADDR)); server_addr.sin_family = Af_inet;server_addr.sin_addr.s_addr = htonl (inaddr_any); server_addr.sin_port = Htons (Atoi ( ARGV[1]); Bind (Server_sock, (struct sockaddr*) &server_addr,sizeof(SERVER_ADDR));// ListenListen (Server_sock, 5);// Acceptsocklen_t client_size=sizeof(client_addr); client_sock = Accept (Server_sock, (struct sockaddr*) &client_addr, &client_size);Char buf[Buf_size];int Str_len; while(1) {Str_len = Read (Client_sock, buf, buf_size);if(Str_len = = 0) { Break; } write (Client_sock, buf, Str_len);} Close (Server_sock); close (Client_sock);
Client
int Server_sock;struct sockaddr_in server_addr; server_sock = socket (af_inet, sock_stream, 0); memset (&server_addr, 0,sizeof(SERVER_ADDR)); server_addr.sin_family = Af_inet;inet_aton (argv[1], &server_addr.sin_addr); server_addr.sin_port = Htons (Atoi ( ARGV[2]); Connect (Server_sock, (struct sockaddr*) &server_addr,sizeof(SERVER_ADDR));Char buf[Buf_size+1];int Str_len; while(1) {printf ("Send to Server (q/q to quit):"); Fgets (buf, Buf_size, stdin);if(strcmp (BUF,"Q\N") = = 0 | | strcmp (BUF,"Q\N") = = 0) { Break; } Str_len = Write (Server_sock, buf, strlen (BUF)); Read (Server_sock, buf, buf_size); Buf[str_len] = 0; printf"from server:%s\N", buf);} Close (Server_sock);
A better client-side implementation
int Str_len; printf"Send to Server (q/q to quit):"); Fgets (buf, Buf_size, stdin);if(strcmp (BUF,"Q\N") = = 0 | | strcmp (BUF,"Q\N") = = 0) { Break; } Str_len = Write (Server_sock, buf, strlen (BUF));---read (Server_sock, buf, buf_size); + + +intstr_cnt = 0;+++intStr_read = 0;+++ while(Str_cnt < Str_len) {+ + + Str_read = Read (Server_sock, &buf[str_cnt], buf_size); + + + str_cnt + = str_read;+++} Buf[str_len] = 0; printf"from server:%s\N", buf);
TCP/IP network programming (transcription note 1)--TCP