Non-connected communication is done through the UDP (User Datagram Protocol)/IP (Internet Protocol) protocol, which does not guarantee reliable data transfer, but can send data to multiple destinations or receive multiple source data. Compared to TCP and other connection communication, no connection communication as long as the service side first create sockets with socket (), and then through the bind () binding to specify the port, do not have to call listen (), accept (), only need to wait for the data.
UDP usage Scenarios: 1. The network data is mostly short message; 2. There is a large number of client;3. No special requirements for data security (after the message is sent, it is not possible to know if it is safe and complete); 4. The network burden is very heavy, but the response speed is high. Applications such as: C/S network application of network video conferencing system.
Client program Flow
Step1 initializing the socket library
Step2 Creating sockets
Socket sclient = socket (af_inet, SOCK_DGRAM, 0);
step3 Fill in the server address
sockaddr_in server;
memset (&server, 0, sizeof (sockaddr_in));
server.sin_family = af_inet;
SERVER.SIN_ADDR.S_ADDR = inet_addr (argv[1]);
Server.sin_port = htons ((u_short) atoi (argv[2]));
STEP4 Communication with the server (data communication) for information processing
(Send data)
Char buff[512] = {0};
strcpy (Buff, "I am Client");
int nret = sendto (sclient, Buff, strlen (buff) +1, 0, (struct sockaddr*) &server, sizeof (server));
(Receive data)
Char buff[512];
int naddrlen = sizeof (server);
memset (buff, 0, sizeof (buff));
Nret = Recvfrom (sclient, buff, sizeof (buff), 0, (struct sockaddr*) &server, &naddrlen);
STEP5 closing sockets after communication ends
STEP6 uninstalling the socket library
Server-Side Program flow
Step1 initializing the socket library
Step2 Creating sockets
Socket slisten= Socket (af_inet,sock_dgram,0)
step3 Create a local entity, fill in the native address information
Sockaddr_in Local;
memset (&local, 0, sizeof (local));
local.sin_family = af_inet;
LOCAL.SIN_ADDR.S_ADDR = Inaddr_any;
Local.sin_port = htons ((u_short) 8888);
STEP4 binding a fixed port
Bind (Slisten, (struct sockaddr *) &local, sizeof (local));
step5 receive client datagrams for processing and communication
Receive data
struct sockaddr_in from;
memset (&from, 0, sizeof (from));
int fromlen = sizeof (from);
Char buff[512] = {0};
Recvfrom (slisten,buff, sizeof (buff), 0, (struct sockaddr*) &from, &fromlen);
Send data
Char buff[512] = {0};
strcpy (Buff, "I am Server");
SendTo (Slisten, Buff, strlen (buff+1), 0, (struct sockaddr*) &from, Fromlen);
STEP6 closing sockets after communication ends
Closesocket (Slisten);
STEP7 uninstalling the socket library
Network programming-simple UDP client/server mode