Uncover the veil of socket programming (keep yourself looking slowly)

Source: Internet
Author: User
Tags htons

You're not a stranger to TCP/IP, UDP,socket programming. With the development of network technology, these words are filled with our ears. Then I would like to ask:

1. What is TCP/IP,UDP?
2. where is the socket?
3. What is a socket?
4. Will you use them?

What is TCP/IP ,UDP ?

TCP/IP (transmission Control protocol/internet Protocol) is a protocol/inter-network protocol, an industry-standard set of protocols designed for wide area networks (WANs).
UDP (user Data Protocol, Subscriber Datagram Protocol) is the protocol that corresponds to TCP. It is a part of the TCP/IP protocol family.
Here is a diagram showing the relationship of these protocols.



Figure 1

The TCP/IP protocol family includes transport layer, network layer, and link layer. Now you know the relationship between TCP/IP and UDP.
Socket where is it?
In Figure 1, we don't see the socket shadow, so where is it? Or use a diagram to speak, at a glance.



Figure 2

The original socket is here.
Socket What is it?
A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, thesocket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol.
Will you use them?
Predecessors have done a lot of things to us, the communication between the network is a lot simpler, but after all, there is still a lot of work to do. Previously heard socket programming, think it is more advanced programming knowledge, but as long as understand how the socket programming principle, the mysterious veil also opened.
A scene in the life. You have to call a friend, dial first, a friend hears a phone call, and then you and your friend establish a connection, you can talk. When the communication is over, hang up the phone and end the conversation. the scene in life explains this work principle, perhaps the TCP/IP protocol family is born in the life, this is not necessarily.

Figure 3

Start with the server side. The server-side initializes the Socket, then binds to the port (BIND), listens to the port (listen), calls the accept block, waits for the client to connect. At this point if a client initializes a Socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at the end.
Here I give a simple example, we are going to the TCP protocol this way (see Figure 2). Examples are written in MFC and run with the following interface:



Figure 4



Figure 5

The client enters the server-side IP address and sends the data, then presses the Send button, the server side receives the data, and then responds to the client. The client reads the data of the response, which is displayed on the interface.
Here are the functions that receive data 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-side:

On the server side, the primary is to start the socket and the listener thread.

#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);

The IP address is set to Inaddr_any, allowing the system to automatically get the IP address of the machine .

Local.sin_addr. S_un. S_addr=inaddr_any;

Initialize Socket

m_listening = socket (af_inet,sock_stream,0);

if (m_listening = = Invalid_socket)

{

return;

}

Bind the local address to the socket you created

if (Bind (m_listening, (LPSOCKADDR) &local,sizeof (local)) = = Socket_error)

{

Closesocket (m_listening);

return;

}

Creates a listener thread, which also responds to an interface operation.

M_hlistenthread =:: CreateThread (Null,0,listenthread,this,0,&dwthreadid);

M_startbtn.enablewindow (FALSE);

M_stopbtn.enablewindow (TRUE);

}

Listener thread Functions:
DWORD WINAPI cserverdlg::listenthread (LPVOID lpparam)
{

cserverdlg* Pdlg = (cserverdlg*) Lpparam;

if (Pdlg = = NULL)

return 0;

SOCKET Listening = pdlg->m_listening;

Start listening for a client connection.

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 there is a client connection, or more wasted CPU resources.

Connectsocket = Accept (Listening, (sockaddr*) &clientaddr,&nlen);

To the IP address of the client .

Char *paddrname = Inet_ntoa (CLIENTADDR.SIN_ADDR);

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

The request data is displayed on the interface.

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 side has been listening for a client connection, if there is a connection, processing the client's request, giving a response, and then continuing to listen.

Client:

Send function for client:

#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);

Turn the IP address in the form of a string into the form required by the IN_ADDR structure.

Dwip = inet_addr (Sztext);

M_requestedit.getwindowtext (Sztext,max_path);

Sockaddr_in Local;

SOCKET sockettmp;

Must be af_inet to indicate that the socket is communicating 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 Socket

Sockettmp=socket (af_inet,sock_stream,0);

Connecting to a server

if (Connect (sockettmp, (LPSOCKADDR) &local,sizeof (local)) < 0)

{

Closesocket (SOCKETTMP);

MessageBox ("Connection server failed. ");

return;

}

Send the request, only 100 bytes for simple, and 100 bytes on the server side .

Send (sockettmp,sztext,100);

Reads the data returned by the server side.

memset (Sztext,0,max_path);

Receives the server-side response.

Receive (sockettmp,sztext,100);

TCHAR Szmessage[max_path];

memset (Szmessage,0,max_path);

strcat (Szmessage,sztext);

The response data is displayed on the interface.

M_replybtn.setwindowtext (szmessage);

Closesocket (SOCKETTMP);

}

The client completes a communication on a function. Why do IP addresses use 127.0.0.1 here? With this IP address, the server side and the client can run on the same machine, so debugging is much easier. Of course you can run the server program on your friend's machine (I tested it on the LAN ), run the client program on your own machine , and of course the IP address you enter is the IP address of your friend's machine .
Simple theory and practice have said, now socket programming is not mysterious it? I hope you have some help.

Uncover the veil of socket programming (keep yourself looking slowly)

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.