The veil of socket programming

Source: Internet
Author: User
Tags htons

Are you familiar with TCP/IP, UDP, and socket programming? With the development of network technology, these words are filled with our ears. So I want to ask:

1. What are TCP/IP and UDP?
2. Where is the socket?
3. What is socket?
4. Will you use them?

What is TCP/IP, UDP?

TCP/IP (Transmission Control Protocol/Internet Protocol) is an industrial standard protocol set designed for WANs.
User Data Protocol (UDP) is the protocol corresponding to TCP. It belongs to the TCP/IP protocol family.
The following figure shows the relationship between these protocols.



Figure 1

TCP/IP protocol families include transport layer, network layer, and link layer. Now you know the relationship between TCP/IP and UDP.
SocketWhere?
In Figure 1, we don't see the socket shadow, so where is it? You can still use graphs to speak clearly.

 



Figure 2

The original socket is here.
SocketWhat is it?
Socket is an intermediate software abstraction layer for communications between the application layer and the TCP/IP protocol family. It is a group of interfaces. In the design mode, socket is actually a facade mode, which hides the complex TCP/IP protocol family behind the socket interface. for users, a set of simple interfaces are all, let the socket organize the data to conform to the specified protocol.
Will you use them?
Our predecessors have already done a lot for us, and the communication between networks is much simpler, but after all there is still a lot of work to do. I have heard about socket programming before and think it is a relatively advanced programming knowledge. But as long as I understand the working principle of socket programming, the mysterious veil will be uncovered.
A scenario in life. You need to call a friend to make a dial-up call. When a friend hears the ringtone and calls the phone, you and your friend can establish a connection to speak. After the communication is over, stop the call. The scenario in life explains this working principle. Maybe the TCP/IP protocol family is born in life, which is not necessarily true.

Figure 3

Start with the server. The server first initializes the socket, then binds it to the port (BIND), listens to the port (Listen), calls accept, and waits for the client to connect. At this time, if a client initializes a socket and connects to the server (CONNECT), if the connection is successful, the connection between the client and the server is established. The client sends a data request. The server receives the request and processes the request. Then, the response data is sent to the client. The client reads the data and closes the connection. The interaction ends.
Here is a simple example. We are following the TCP protocol path (see figure 2 ). The example is written in MFC. The running interface is as follows:

 



Figure 4

 



Figure 5

Enter the Server IP address and sent data on the client, and then press the send button. The server receives the data and then responds to the client. The client reads the response data and displays it on the interface.
The following functions receive and send data:

Int receive (socket FD, char * sztext, int Len)

{
Int CNT;
Int RC;
CNT = Len;

While (CNT> 0)
{
Rc = Recv (FD, sztext, CNT, 0 );
If (rc = socket_error)
{
Return-1;
}

If (rc = 0)

Return len-CNT;

Sztext + = RC;

CNT-= RC;

}

Return Len;

}

Int send (socket FD, char * sztext, int Len)
{

Int CNT;

Int RC;

CNT = Len;

While (CNT> 0)

{

Rc = Send (FD, sztext, CNT, 0 );

If (rc = socket_error)

{

Return-1;

}

If (rc = 0)

Return len-CNT;

Sztext + = RC;

CNT-= RC;

}

Return Len;

}

Server:

On the server side, the socket and listening thread are started.

# Define default_port 2000.

Void cserverdlg: onstart ()

{

Sockaddr_in local;

DWORD dwthreadid = 0;

Local. sin_family = af_inet;

// Set the port to default_port.

Local. sin_port = htons (default_port );

// Set the IP address to inaddr_any so that the system can automatically obtain the IP address of the local machine.

Local. sin_addr.s_un.s_addr = inaddr_any;

 

// Initialize the socket

M_listening = socket (af_inet, sock_stream, 0 );

If (m_listening = invalid_socket)

{

Return;

}

// Bind the local address to the created socket

If (BIND (m_listening, (lpsockaddr) & Local, sizeof (local) = socket_error)

{

Closesocket (m_listening );

Return;

}

// Create a listening thread to respond to operations on the interface.

M_hlistenthread =: createthread (null, 0, listenthread, this, 0, & dwthreadid );

M_startbtn.enablewindow (false );

M_stopbtn.enablewindow (true );

}

Listening thread function:
DWORD winapi cserverdlg: listenthread (lpvoid lpparam)
{

Cserverdlg * pdlg = (cserverdlg *) lpparam;

If (pdlg = NULL)

Return 0;

 

Socket listening = pdlg-> m_listening;

// Start listening for whether a client connection exists.

If (Listen (listening, 40) = socket_error)

{

Return 0;

}

Char szbuf [max_path];

// Initialization

Memset (szbuf, 0, max_path );

While (1)

{

Socket connectsocket;

Sockaddr_in clientaddr;

Int nlen = sizeof (sockaddr );

// Blocking until a client connection exists. Otherwise, CPU resources are wasted.

Connectsocket = accept (listening, (sockaddr *) & clientaddr, & nlen );

// All to the Client IP address.

Char * paddrname = inet_ntoa (clientaddr. sin_addr );

Pdlg-> receive (connectsocket, szbuf, 100 );

// The request data is displayed on the page.

Pdlg-> setrequesttext (szbuf );

Strcat (szbuf, ": I am an old cat, received (");

Strcat (szbuf, paddrname );

Strcat (szbuf ,")");

// Send response data to the client

Pdlg-> send (connectsocket, szbuf, 100 );

}

Return 0;

}

The server constantly monitors whether a client connection exists. If a connection exists, the server processes the client request, responds to the request, and then continues to listen.

Client:

Client sending function:

# Define default_port 2000.

Void cclientdlg: onsend ()

{

DWORD dwip = 0;

Tchar sztext [max_path];

Memset (sztext, 0, max_path );

M_ip.getwindowtext (sztext, max_path );

// Convert a string-type IP address to an in_addr structure.

Dwip = inet_addr (sztext );

M_requestedit.getwindowtext (sztext, max_path );

 

Sockaddr_in local;

Socket sockettmp;

// It Must Be af_inet, indicating that the socket can communicate in the Internet Domain

Local. sin_family = af_inet;

// Port number

Local. sin_port = htons (default_port );

// The IP address of the server.

Local. sin_addr.s_un.s_addr = dwip;

//// Initialize the socket

Sockettmp = socket (af_inet, sock_stream, 0 );

// Connect to the server

If (connect (sockettmp, (lpsockaddr) & Local, sizeof (local) <0)

{

Closesocket (sockettmp );

MessageBox ("failed to connect to the server. ");

Return;

}

// Send a request. In this case, only 100 bytes are sent, and 100 bytes are allowed on the server side.

Send (sockettmp, sztext, 100 );

// Read the data returned by the server.

Memset (sztext, 0, max_path );

// Receives the response from the server.

Receive (sockettmp, sztext, 100 );

 

Tchar szmessage [max_path];

Memset (szmessage, 0, max_path );

Strcat (szmessage, sztext );

// Response data is displayed on the page.

M_replybtn.setwindowtext (szmessage );

Closesocket (sockettmp );

}

The client completes communication with a function. Why is the IP address 127.0.0.1 used here? By using this IP address, the server and client can run on the same machine, making debugging much easier. Of course, you can run the server program on your friend's machine (I tested it in the LAN) and run the client program on your machine, of course, the Entered IP address should be the IP address of your friend's machine.
I have put it all in Simple Theory and Practice. Isn't socket programming mysterious now? Hope to help you.

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.