Network Programming-TCP-based programming and UDP-based programming

Source: Internet
Author: User
Tags htons

Network programming can be divided into TCP-based network programming and UDP-based network programming. TCP is a connection-oriented byte stream and is often used for reliable network transmission. UDP is a datagram-based connectionless network transmission, which is commonly used for instant communication.

Whether it is based on TCP or UDP-based programming, there are fixed steps to follow. As long as you understand these steps, the implementation is relatively simple. The following describes the detailed steps of TCP and UDP-based network programming and the implementation example.

Before introducing network programming, we should first note that the Winsock function is an excuse for network programming provided by Windows. Whether it is TCP-based or UDP-based network programming, before programming, you must first load the Winsock library.

1. TCP-based network applications

Network applications are all based on the C/S (Client/Server) mode. Therefore, when developing network applications, you must not only develop server applications but also client applications. The steps for developing server applications and client applications are slightly different. The following describes the detailed steps for TCP-based network application development:

Server application: client application:

1. Create socket 1. Create socket

2. bind the socket to the specified local IP address and port.

3. Set the socket to the listening mode (listen) and prepare to accept client requests. 2. Send the connection request (connect) to the server)

4. Wait for the client request to arrive (accept) and return a new socket for communication.

5. The server and client communicate with each other (send/recv) 3. The server and client communicate with each other (send/recv)

6. Return and continue waiting for the arrival of new client requests

7. Disable socket 4. Disable socket

Note: The server needs to bind a port to listen to client requests. Communication starts only after the request is received. The client only needs to send the request first, as long as the request is received, it can communicate.

Before understanding the sample code, introduce some knowledge points and functions:

First: in network programming, IP addresses and port numbers are used. For example, the IP addresses and port numbers must be included in the bind () and accept () functions, in Windows API, there is a SOCKADDR_IN struct that stores information about IP addresses and port numbers.

Second, the IP address to be bound to the server should use the (INADDR_ANY) attribute to indicate that the server can accept connection requests sent from any port, because some machines may have multiple NICs, therefore, there may be multiple IP addresses. This setting can facilitate subsequent program development.

Third: Network byte order is used in network communication. The local byte order of intel machines is different from the storage format of the network byte order, so use the desired function for conversion.

Inet_addr () converts the IP address in dotted decimal format to u_long type.

Inet_ntoa () converts an in_addr structure parameter to an IP address in dotted-decimal format.

Htonl () converts a u_long IP address from the host byte to the network byte

Htons () converts u_short IP addresses from the host's byte order to the network's byte order

Fourth, the Winsock library is used for network programming. Therefore, not only the winsock header file must be loaded, but also the ws2_32.lib dynamic link library must be bound. There are two methods to bind a dynamic link library. The first is to add ws2_32.lib to the Link Library of Link in the "properties" of the project. The second method is to add the code in the source file of the project: # pragma comment (lib, "ws2_32.lib.

/*************************************** ***********************
Sample Code of TCP-based server application
**************************************** ************************/

# Include "stdafx. h"
# Include <stdlib. h>
# Include <Winsock2.h>
# Include <stdio. h>
Void main ()
{
/*************************************** ***********************
Load the Winsock Library
**************************************** ************************/
WORD wVersionRequested;
WSADATA 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;
}
/*************************************** ***********************
Step 1: Create a Winsock socket
**************************************** ************************/
SOCKET sockSrv = socket (AF_INET, SOCK_STREAM, 0 );
/*************************************** ***********************
Step 2: bind the created socket to the local address and port
**************************************** ************************/
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, (const sockaddr *) & addrSrv, sizeof (SOCKADDR ));
/*************************************** ***********************
Step 3: Set the socket to the listening mode and prepare to accept client requests
**************************************** ************************/
Listen (sockSrv, 5 );
/*************************************** ***********************
Step 4: accept client requests
Step 5: receive messages from the client and send messages to the client
Step 6: Return wait
Step 7: Disable socket
**************************************** ************************/
SOCKADDR_IN addrClient;
Int len = sizeof (SOCKADDR );
While (1)
{
SOCKET sockCon = accept (sockSrv, (SOCKADDR *) & addrClient, & len );
Char sendBuf [100];
Sprintf (sendBuf, "This is server, Welcome % s", inet_ntoa (addrClient. sin_addr ));
Send (sockCon, sendBuf, strlen (sendBuf) + 1, 0 );
Char recvbuf [100];
Recv (sockCon, recvbuf, strlen (recvbuf) + 1, 0 );
Printf ("% s \ n", recvbuf );
Closesocket (sockCon );
}
System ("PAUSE ");
}

/*************************************** ***********************
TCP-based client application sample code
**************************************** ************************/

# Include "stdafx. h"
# Include <stdlib. h>
# Include <Winsock2.h>
# Include <stdio. h>
Void main ()
{
/*************************************** ***********************
Load the Winsock Library
**************************************** ************************/
WORD wVersionRequested;
WSADATA 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;
}
/*************************************** ***********************
Step 1: Create a Winsock socket
**************************************** ************************/
SOCKET sockClient = socket (AF_INET, SOCK_STREAM, 0 );
/*************************************** ***********************
Step 2: Send a connection request to the server
**************************************** ************************/
SOCKADDR_IN addrSrv;
AddrSrv. sin_addr.S_un.S_addr = inet_addr ("127.0.0.1 ");
AddrSrv. sin_family = AF_INET;
AddrSrv. sin_port = htons (6000 );
Connect (sockClient, (const sockaddr *) & addrSrv, sizeof (SOCKADDR ));
/*************************************** ***********************
Step 3: communication between the client and the server
**************************************** ************************/
Char recvbuf [100];
Recv (sockClient, recvbuf, strlen (recvbuf) + 1, 0 );
Printf ("% s", recvbuf );
Send (sockClient, "My name is zhangsan Client", strlen ("My name is zhangsan Client") + 1, 0 );
Closesocket (sockClient );

WSACleanup ();

System ("PAUSE ");

}

Run the server program before running the client program. The running result is as follows:

2. UDP-based network applications

The preceding describes TCP-based network applications. For convenience of comparison, the following describes the design of UDP-based network applications.

As above, we should first accept the development steps of UDP-based network applications:

Server application: client application:

1. Create socket 1. Create socket

2. bind the socket to the specified local IP address and port. 2. Send a message to the server)

3. If a message is detected, the system will receive the message (recvfrom)

4. Disable socket 3. Disable socket

Note: because UDP-based network applications are connectionless, server listening and client connection requests are not required. It is easier to implement than TCP connection-oriented and is suitable for instant communication. The main functions and methods used are roughly the same as those used in TCP design. The sample code is as follows:

/*************************************** ***********************
UDP-based server application sample code
**************************************** ************************/

# Include "stdafx. h"
# Include <stdlib. h>
# Include <Winsock2.h>
# Include <stdio. h>

# Pragma comment (lib, "ws2_32.lib ")
Void main ()
{
/*************************************** ***********************
Load the Winsock Library
**************************************** ************************/
WORD wVersionRequested;
WSADATA 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;
}
/*************************************** ***********************
Step 1: Create a Winsock socket
**************************************** ************************/
SOCKET sockSrv = socket (AF_INET, SOCK_DGRAM, 0 );
/*************************************** ***********************
Step 2: bind the created socket to the specified address and port
**************************************** ************************/
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, (const sockaddr *) & addrSrv, sizeof (SOCKADDR ));
/*************************************** ***********************
Step 3: Wait for and receive messages sent from the client
**************************************** ************************/
SOCKADDR_IN addrClient;
Char recvBuf [100];
Int len = sizeof (SOCKADDR );
Recvfrom (sockSrv, recvBuf, 100,0, (sockaddr *) & addrClient, & len );
Printf ("% s", recvBuf );
Char sendBuf [100];
Sprintf (sendBuf, "This is UDP Serve! Welcome % s ", inet_ntoa (addrClient. sin_addr ));
Sendto (sockSrv, sendBuf, strlen (sendBuf) + 1, 0,
(Const sockaddr *) & addrClient, sizeof (SOCKADDR ));
Closesocket (sockSrv );

WSACleanup ();
System ("pause ");
}

/*************************************** ***********************
UDP-based client application sample code
**************************************** ************************/

# Include "stdafx. h"
# Include <stdlib. h>
# Include <Winsock2.h>
# Include <stdio. h>

# Pragma comment (lib, "ws2_32.lib ")
Void main ()
{
/*************************************** ***********************
Load the Winsock Library
**************************************** ************************/
WORD wVersionRequested;
WSADATA 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;
}
/*************************************** ***********************
Step 1: Create a Winsock socket
**************************************** ************************/
SOCKET sockClient = socket (AF_INET, SOCK_DGRAM, 0 );
/*************************************** ***********************
Step 1: send messages to the server
**************************************** ************************/
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 );
Sendto (sockClient, "My name is UDP Client! ", Strlen (" My name is UDP Client! ") + 1, 0,
(Const sockaddr *) & addrClient, sizeof (SOCKADDR ));
Char recvBuf [100];
Int len = sizeof (SOCKADDR );
Recvfrom (sockClient, recvBuf, 100,0, (sockaddr *) & addrClient, & len );
Printf ("% s", recvBuf );
Closesocket (sockClient );
WSACleanup ();

System ("pause ");
}

The running result is as follows:

<Script type = text/javascript> if ($! = JQuery) {$ = jQuery. noConflict ();} var isLogined = false; var cb_blogId = 96439; var cb_entryId = 2208677; var cb_blogApp = "chengfeng736"; var cb_blogUserGuid = "login "; var cb_entryCreatedDate = '2014/1/12 15:13:00 '; </script> from: Wind 2011/10

Related Article

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.