Introduction to socket-based UDP and TCP programming

Source: Internet
Author: User
Tags bind socket port number server port htons
Http://blog.chinaunix.net/uid-11848011-id-96439.html
First, the overview of TCP (Transmission Control Protocol) and UDP (User Datagram Protocol is the network architecture TCP/IP model in the Transport layer layer of the two different communication protocols. TCP: Transmission Control Protocol, a connection-oriented protocol that provides a reliable full-duplex byte stream for user processes, and a TCP socket interface is a type of byte-throttle socket Interface (stream socket). UDP: User Datagram Protocol. UDP is a non-connectivity protocol. The UDP socket interface is one of the datagram socket interfaces (datagram sockets). Ii. Introduction to TCP and UDP 1) Basic TCP client-server programming framework

Description: (Three-way handshake)
1. The client sends a SYN segment (synchronous sequence number) that indicates the server port to which the customer intends to connect, and the initialization sequence number (ISN).
2. The server sends back the SYN message segment that contains the initial sequence number of the server as a reply. At the same time, the confirmation sequence number (ACK) is set to customer's ISN plus 1 to confirm the customer's SYN message segment. A SYN will occupy an ordinal number.
3. The customer must set the confirmation number to the server's ISN plus 1 to confirm the SYN message segment of the server.

2) Basic TCP client-server programming basic framework Flowchart

3) comparison between UDP and TCP: From the above flowchart we can clearly see that UDP does not have three handshake process. Simply put. UDP handles less detail than TCP. UDP does not guarantee that a message is delivered to (it also reports that the message is not delivered to) the destination. UDP also does not guarantee the order in which packets are sent. UDP sends out the data only to expect it to reach its destination. TCP pros and Cons: Advantages:
1. TCP provides an acceptable way to explicitly create and terminate a connection.
2. TCP guarantees reliable, sequential (packets received in the order in which they are sent) and data transfers that are not duplicated.
3. TCP processing Flow control.
4. Allow data to take precedence
5. If the data is not delivered to, then the TCP socket interface returns an error status condition.
6. TCP handles large chunks of data by maintaining continuous and dividing chunks into smaller shards. -No programmer knows the disadvantage: TCP must create (and maintain) a connection when transferring data. This connection adds overhead to the communication process, making it slower than the UDP speed. UDP pros and Cons:
1. UDP does not require a connection to be maintained
2. UDP does not have the overhead of receiving a packet (or automatically retransmission when the packet does not arrive correctly) due to the recipient's approval.
3. UDP is designed to be used for short applications and control messages
4. UDP requires less network bandwidth than TDP on the basis of a packet connected to a packet. Socket programming Socket interface The Api,socket interface of a TCP/IP network defines a number of functions or routines that programmers can use to develop applications on TCP/IP networks. To learn TCP/IP network programming on the Internet, you must understand the socket interface. The socket interface Designer is the first to put the interface in the UNIX operating system. If you understand the input and output of UNIX systems, it is easy to understand the socket. The network socket data transmission is a special i/o,socket is also a kind of file descriptor. The socket also has a function call socket () that resembles an open file, which returns an integer socket descriptor, followed by connection creation, data transfer, and so on, through the socket. There are two common types of sockets: Streaming Sockets (SOCK_STREAM) and datagram Sockets (SOCK_DGRAM). Streaming is a connection-oriented socket for connection-oriented TCP service applications; A datagram socket is a non-connected socket that corresponds to a non-connected UDP service application. 1, Socket Call library functions are: Create sockets
Socket (Af,type,protocol) establishes address and socket connections
Bind (sockid, local addr, Addrlen) server-side listener requests for clients
Listen (Sockid, Quenlen) establishing a server/client connection (connection-oriented TCP)
Client Request Connection
Connect (Sockid, destaddr, Addrlen)
Server side waits for client connection requests to be received from a socket numbered Sockid
Newsockid=accept (sockid,clientaddr, Paddrlen) Send/Receive data
Connection oriented: Send (Sockid, buff, Bufflen)
Recv ()
For no connection: sendto (sockid,buff,..., Addrlen)
Recvfrom () Release socket
Close (Sockid) 2, TCP/IP application Programming Interface (API) Server workflow: First call the socket function to create a socket, and then call the BIND function to bind it to the native address and a local port number, Then call listen to listen on the corresponding socket, and when Accpet receives a connection service request, a new socket is generated. The server displays the IP address of the client and sends the string "Hi,i am server!" to the client through a new socket. Finally, close the socket.

Main ()
{
int sock_fd,client_fd; /*SOCK_FD: Monitor SOCKET;CLIENT_FD: Data transfer Socket */
struct sockaddr_in ser_addr; /* Native Address information */
struct sockaddr_in cli_addr; /* Client Address information */
Char msg[max_msg_size];/* buffer */
Ser_sockfd=socket (af_inet,sock_stream,0);/* Create a connected socket */
if (ser_sockfd<0)
{/* Create failed */
fprintf (stderr, "Socker error:%s\n", Strerror (errno));
Exit (1);
}
/* Initialize the server address */
addrlen=sizeof (struct sockaddr_in);
Bzero (&ser_addr,addrlen);
Ser_addr.sin_family=af_inet;
Ser_addr.sin_addr.s_addr=htonl (Inaddr_any);
Ser_addr.sin_port=htons (Server_port);
if (bind (SER_SOCKFD, struct sockaddr*) &ser_addr,sizeof (struct sockaddr_in)) <0)
{/* bind failed */
fprintf (stderr, "Bind error:%s\n", Strerror (errno));
Exit (1);
}
/* Listen for client requests */
if (Listen (Ser_sockfd,backlog) <0)
{
fprintf (stderr, "Listen error:%s\n", Strerror (errno));
Close (SER_SOCKFD);
Exit (1);
}
while (1)
{/* Waiting to receive client connection requests */
Cli_sockfd=accept (SER_SOCKFD, (struct sockaddr*) & Cli_addr,&addrlen);
if (cli_sockfd<=0)
{
fprintf (stderr, "Accept error:%s\n", Strerror (errno));
}
Else
{/* Start service */
Recv (cli_addr,msg,max_msg_size,0); /* Accept Data */
printf ("received a connection from%SN", Inet_ntoa (CLI_ADDR.SIN_ADDR));
printf ("%s\n", msg);/* print out on the screen */
strcpy (msg, "Hi,i am server!");
Send (Cli_addr,msg,sizeof (msg), 0); /* Data sent */
Close (CLI_ADDR);
}
}
Close (SER_SOCKFD);
}


Client Workflow: First call the socket function to create a socket and then call the BIND function to bind it to the native address and a local port number, request a connection to the server, and send the string "Hi,i am client!" to the client via a new socket. Finally, close the socket.

Main ()
{
int cli_sockfd;/* Client Socket */
int Addrlen;
Char seraddr[14];
struct sockaddr_in address of the ser_addr,/* server */
Address of the cli_addr;/* client */
Char msg[max_msg_size];/* buffer */
GETSERVERADDR (SERADDR);
Cli_sockfd=socket (af_inet,sock_stream,0);/* Create a connected socket */
if (ser_sockfd<0)
{/* Create failed */
fprintf (stderr, "Socker error:%s\n", Strerror (errno));
Exit (1);
}
/* Initialize the client address */
addrlen=sizeof (struct sockaddr_in);
Bzero (&ser_addr,addrlen);
Cli_addr.sin_family=af_inet;
Cli_addr.sin_addr.s_addr=htonl (Inaddr_any);
cli_addr.sin_port=0;
if (Bind (CLI_SOCKFD, (struct sockaddr*) &cli_addr,addrlen) <0)
{
/* Failure of the bar */
fprintf (stderr, "Bind error:%s\n", Strerror (errno));
Exit (1);
}
/* Initialize the server address */
addrlen=sizeof (struct sockaddr_in);
Bzero (&ser_addr,addrlen);
Ser_addr.sin_family=af_inet;
SER_ADDR.SIN_ADDR.S_ADDR=INET_ADDR (SERADDR);
Ser_addr.sin_port=htons (Server_port);
if (Connect (cli_sockfd, struct sockaddr*) &ser_addr,&addrlen)/*/Request Connection */
{
/* Connection Failed */
fprintf (stderr, "Connect error:%s\n", Strerror (errno));
Close (CLI_SOCKFD);
Exit (1);
}
strcpy (msg, "Hi,i am client!");
Send (Sockfd,msg,sizeof (msg), 0);/* Sends data */
Recv (sockfd,msg,max_msg_size,0); /* Accept Data */

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.