Windows Programming _ sun Xin C ++ lesson14 Network Programming

Source: Internet
Author: User
Tags htons

Windows Programming _ sun Xin C ++ lesson14 Network Programming
Highlights of this section:
1. Introduction to the Network Protocol Reference Model
2. Socket Overview
3. Network byte sequence
4. Introduction to Client/Server Modes
5. Implementation of Windows Sockets
6. Preparation of Windows network programming functions
7. TCP-based socket programming
8. UDP-based socket programming
//************************************** **************************************** *******
1. Introduction to the Network Protocol Reference Model
OSI Layer-7 Reference Model the layer-4 TCP/IP model involves a wealth of theoretical knowledge. For more information, see Xie xiiren's "Computer Network".
Here, we will only list the diagrams for help understanding below:

2. Socket Overview
The socket exists in the communication area. A communication region is also called an address family. It is an abstract concept used to combine the public features of processes that communicate through sockets.
Generally, a socket only exchanges data with a socket in the same region (cross-region communication is also possible, but this can only be achieved after a certain conversion process is executed ). Windows Sockets only supports one communication region: af_inet, which is used by processes that communicate with the Internet protocol cluster.
3. Network byte sequence
Different computers store multi-byte values in different order. Some machines store low-byte values at the starting address (low-level first-saving), and some machines store high-byte values at the starting address (high-level first-saving ). Intel-based CPU, that is, our Commonly Used PC uses low-level memory first. To ensure data correctness, you must use the specified network byte sequence in the network protocol. The TCP/IP protocol uses a 16-bit integer and a 32-bit integer high-position first storage format.
4. For details about the Client/Server mode, See Xie xiiren computer network.
As shown in the following figure:

5. Implementation of Windows Sockets
(1) Windows Sockets is extended from Berkeley socket and provided to us as a dynamic link library. Windows Sockets expansion mainly provides some asynchronous functions, and adds a network event asynchronous selection mechanism that complies with the Windows message driver features.
(2) socket type
Streaming socket (sock_stream) provides connection-oriented and reliable data transmission services. It can send data without errors or duplicates and receive data in the order of sending. It is implemented based on the TCP protocol.
The datagram socket (sock_dgram) provides the connectionless service. Data packets are sent in the form of independent packets, without error-free guarantee. data may be lost or duplicated, and the receiving order is disordered. This is implemented based on UDP protocol.
The original socket (sock_ram) is not described here.
6. Preparation of Windows network programming functions
(1)
Int wsastartup (
Word wversionrequested, // specify the lowest version for the High-byte Windows Sockets version,
// Low byte indicates the master version
Lpwsadata //
);
This function loads the dynamic link library ws2_32.dll. After each successful call, the application must call wsacleanup to release the resources of ws2_32.dll and terminate the use.

(2) Socket socket (
Int AF, // specifies the TCP/IP socket for the address family
Int type, // specify the socket type
Int protocol // The Protocol associated with the specific address family is specified as 0.
The address format and socket category automatically select an appropriate protocol for you
);
Creates a socket bound to the specified service provider.
(3) int BIND (
Socket S, // The socket to be bound
Const struct sockaddr far * Name, // specifies the local address of the socket pointing to the sockaddr pointer
Int namelen // specify the length of the second parameter
);
Used to bind a local address and socket.
Struct sockaddr {
U_short sa_family;
Char sa_data [14];
};
In TCP/IP, we can use the sockaddr_in structure to replace sockaddr so that we can enter the address information.
Struct sockaddr_in {
Short sin_family;
U_short sin_port;
Struct in_addr sin_addr;
Char sin_zero [8];
};
(4) inet_addr converts an IPv4 address string to an appropriate address in the in_addr structure.
Inet_ntoa converts an IPv4 address to a string in the form of A. B. C. D.
Htonl converts the number of 32-bit hosts in the u_long structure to the TCP/IP network in the byte sequence.
Htons converts the number of 16-bit host bytes in a u_short structure to the TCP/IP network byte order.
(5) send data over TCP
Int send (
Socket s,
Const char far * Buf,
Int Len,
Int flags
);
TCP accept data
Int Recv (
Socket s,
Char far * Buf,
Int Len,
Int flags
);
(6) send data over UDP
Int sendto (
Socket s,
Const char far * Buf,
Int Len,
Int flags,
Const struct sockaddr far *,
Int tolen
);
UDP accept data
Int recvfrom (
Socket s,
Char far * Buf,
Int Len,
Int flags,
Struct sockaddr far * from,
Int far * fromlen
);
7. TCP-based socket programming
Note: Add two programs to a project and switch between projects by selecting the components. Start the server first, and then start the client.
The compiling process of the tcp client and the server is as follows:

// The experiment code is as follows:
//************************************** **************************************** *******
// Tcpsrv. cpp
# Include <winsock2.h>
# Include <stdio. h>
Void main ()
{
Word wversionrequested;
Wsadata;
Int err;

Wversionrequested = makeword (1, 1 );
// Load ws2_32.dll
Err = wsastartup (wversionrequested, & wsadata );
If (Err! = 0 ){
Return;
}

If (lobyte (wsadata. wversion )! = 1 |
Hibyte (wsadata. wversion )! = 1 ){
Wsacleanup ();
Return;
}

Socket socketsrv = socket (af_inet, sock_stream, 0); // Step1 create a socket
Sockaddr_in addrsrv;
Addrsrv. sin_addr.s_un.s_addr = htonl (inaddr_any); // network byte
Addrsrv. sin_family = af_inet;
Addrsrv. sin_port = htons (6000); // two bytes of the port number
BIND (socketsrv, (sockaddr *) & addrsrv, sizeof (sockaddr); // Step 2 bind to socket
Listen (socketsrv, 5); // Step3 listener connection request 5 is the queue length
Sockaddr_in addrclient;
Int Len = sizeof (sockaddr); // The initial value must be assigned.
// The server program runs cyclically.
While (1)
{
Socket scoketconn = accept (socketsrv, (sockaddr *) & addrclient, & Len); // Step 4 accept the request addrclient to receive the information of the connection requester

Char sendbuf [100];
Sprintf (sendbuf, "Wellcome! Connect from % s success! ", Inet_ntoa (addrclient. sin_addr ));
Send (scoketconn, sendbuf, strlen (sendbuf) +); // step5 the socket used to send data cannot use a socket in the listening state
Char recvbuf [100];
Recv (scoketconn, recvbuf, 0); // step5 receives data
Printf ("% s \ n", recvbuf );
Closesocket (scoketconn );
}
// The following operations are actually required, but the above is an endless loop, so the following operations are not performed
Closesocket (socketsrv); // close the socket
Wsacleanup (); // terminate database reference
}
//************************************** **************************************** *******
// Tcpclient. cpp
# Include <winsock2.h>
# Include <stdio. h>
Void main ()
{
Word wversionrequested;
Wsadata;
Int err;

Wversionrequested = makeword (1, 1 );

Err = wsastartup (wversionrequested, & wsadata );
If (Err! = 0 ){
Return;
}
If (lobyte (wsadata. wversion )! = 1 |
Hibyte (wsadata. wversion )! = 1 ){
Wsacleanup ();
Return;
}
Socket socketclient = socket (af_inet, sock_stream, 0); // Step1 create a socket
Sockaddr_in addrsrv;
Addrsrv. sin_addr.s_un.s_addr = inet_addr ("127.0.0.1"); // local loop address
Addrsrv. sin_family = af_inet;
Addrsrv. sin_port = htons (6000 );
Connect (socketclient, (sockaddr *) & addrsrv, sizeof (sockaddr); // step2 Connection Request
Char recvbuf [100];
Recv (socketclient, recvbuf,); // receives server data
Printf ("% s \ n", recvbuf );
Char sendbuf [100];
Sprintf (sendbuf, "this is from % s", "liming ");
Send (socketclient, sendbuf, strlen (sendbuf) + 1, 0); // send data
Closesocket (socketclient); // close the socket to release resources
Wsacleanup (); // terminate the reference of the socket Library
}
//************************************** **************************************** *******
After the program is started (note that the server program is started first, and then the client program is started:


//************************************** **************************************** *******
8. UDP-based socket programming
Shows the compiling process of the UDP server and client:

 

// The experiment code is as follows:
//************************************** **************************************** *******
// Netsrv. cpp
# Include <winsock2.h>
# Include <stdio. h>
Void main ()
{
// Load the DLL file
Word wversionrequested;
Wsadata;
Int err;
Wversionrequested = makeword (1, 1 );
Err = wsastartup (wversionrequested, & wsadata );
If (Err! = 0 ){
Return;
}
If (lobyte (wsadata. wversion )! = 1 |
Hibyte (wsadata. wversion )! = 1 ){
Wsacleanup ();
Return;
}
Socket socksrv = socket (af_inet, sock_dgram, 0); // create a UDP-based socket
Sockaddr_in addrsrv;
Addrsrv. sin_addr.s_un.s_addr = htonl (inaddr_any );
Addrsrv. sin_family = af_inet;
Addrsrv. sin_port = htons (6000 );
BIND (socksrv, (sockaddr *) & addrsrv, sizeof (sockaddr); // bind a socket
Char recvbuf [100];
Char sendbuf [100];
Char tempbuf [200];
Sockaddr_in addrclient;
Int Len = sizeof (sockaddr); // listen to the request
While (1)
{
Recvfrom (socksrv, recvbuf, (sockaddr *) & addrclient, & Len); // accept data
If ('q' = recvbuf [0]) // whether the recipient wants to chat
{
Sendto (socksrv, "Q", strlen ("Q") +, (sockaddr *) & addrclient, sizeof (sockaddr); // resend a 'q' to terminate the chat
Printf ("chat end! \ N ");
Break; // terminate the cycle
}
Sprintf (tempbuf, "Message from % s is: % s \ n", inet_ntoa (addrclient. sin_addr), recvbuf );
Puts (tempbuf); // displays accepted data
Printf ("Please reply: \ n ");
Gets (sendbuf );
Sendto (socksrv, sendbuf, strlen (sendbuf) +, (sockaddr *) & addrclient, sizeof (sockaddr); // send data
}
// Process Resource release
Closesocket (socksrv );
Wsacleanup ();
}
//************************************** **************************************** *******
// Netclient. cpp
# Include <winsock2.h>
# Include <stdio. h>
Void main ()
{
Word wversionrequested;
Wsadata;
Int err;

Wversionrequested = makeword (1, 1 );

Err = wsastartup (wversionrequested, & wsadata );
If (Err! = 0)
{
Return;
}

If (lobyte (wsadata. wversion )! = 1 |
Hibyte (wsadata. wversion )! = 1 ){
Wsacleanup ();
Return;
}
Socket sockclient = socket (af_inet, sock_dgram, 0); // create a UDP-based socket
Sockaddr_in addrclient;
Addrclient. sin_addr.s_un.s_addr = inet_addr ("127.0.0.1 ");
Addrclient. sin_family = af_inet;
Addrclient. sin_port = htons (6000 );
Char recvbuf [100];
Char sendbuf [100];
Char tempbuf [200];
Sockaddr_in addrsrv;
Int Len = sizeof (sockaddr );
While (1)
{
Printf ("plase input message \ n ");
Gets (sendbuf );
Sendto (sockclient, sendbuf, strlen (sendbuf) +, (sockaddr *) & addrclient, sizeof (sockaddr); // send data
Recvfrom (sockclient, recvbuf, 100,0, (sockaddr *) & addrsrv, & Len );
If ('q' = recvbuf [0]) // whether to terminate the chat
{
Sendto (sockclient, "Q", strlen ("Q") + 1, 0, (sockaddr *) & addrclient, sizeof (sockaddr ));
Printf ("chat end! \ N ");
Break;
}
Sprintf (tempbuf, "Message from % s is: % s \ n", inet_ntoa (addrsrv. sin_addr), recvbuf );
Puts (tempbuf );
}
// Process Resource release
Closesocket (sockclient );
Wsacleanup ();
}
//************************************** **************************************** *******
After the program is started (note that the server program is started first, and then the client program is started:


//************************************** **************************************** *******
Summary In this section"
1. Identify the Differences Between TCP and UDP
2. Understand Windows Sockets socket
3. Master simple TCP-based, UDP-based server and client Programming
Some parameters in these functions, especially addrclient. sin_addr.s_un.s_addr = inet_addr ("127.0.0.1"), are not very convenient to use and need to be understood.

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.