C # Socket network programming; TCP/IP hierarchical model, port and packet

Source: Internet
Author: User

1. TCP/IP layered model

Of course, here we will only discuss the important layer-4

01. Application Layer (Application Layer): the Application layer is a broad concept. It has some similar system-level TCP/IP applications and Application protocols, as well as many enterprise applications and Internet applications. The http protocol runs at the application layer.

02. Transport Layer (Tanspot): the transport layer includes UDP and TCP. UDP does not check packets, while TCP provides transmission guarantee.

03. Network Layer (Netwok): the network layer protocol consists of a series of protocols, including ICMP, IGMP, RIP, OSPF, and IP (v4, v6.

04. Link: it is also called the interface layer of the physical data network and is responsible for packet transmission.

Next, let's look at the tcp layered model diagram.

It can be seen that the application runs at the application layer, and the TCP header is added before the data at the transmission layer.

The IP header added to the network layer adds frames to the data link layer.

2. Port

Port number range: 0-65535. The total number can be 65536.

By port number can be divided into three categories

(1) WellKnownPorts: from 0 to 1023, they are closely bound to some services. Usually the communication between these ports clearly indicates a service protocol. For example, port 80 is always HTTP Communication.

(2) Registration port (RegisteredPorts): from 1024 to 49151. They are loosely bound to some services. That is to say, many services are bound to these ports, which are also used for many other purposes. For example, many systems process dynamic ports starting from around 1024.

(3) dynamic and/or private ports (Dynamicand/orPrivatePorts): From 49152 to 65535. Theoretically, these ports should not be allocated to the service. In fact, machines usually allocate dynamic ports from 1024.

3. TCP and UDP Packets

Next let's take a look at the TCP and UDP packets.

We can see that both TCP and UDP have a Checksum, but in UDP packets, the checksum is generally not used, which can speed up data transmission, but the data accuracy may be affected. In other words, the Tcp protocol has a checksum to ensure the accuracy of the transmitted data.

3. Socket

The Socket includes the IP address and port number. The program uses Socket to communicate. Socket is equivalent to a component of the operating system. As the communication mechanism between processes, Socket is also called "Socket". It is used to describe the IP address and port number, and is the handle of a communication chain. To put it bluntly, two programs are used for communication.

Comparison of life cases:

Communication between sockets can be analogous to calls in daily life. Before a call, a user must possess a telephone, which is equivalent to applying for a Socket and knowing the number of the other Party. It is equivalent to having a fixed Socket and then dialing a call from the other party, it is equivalent to sending a connection request. If the other party is present and idle, pick up the phone microphone and the two parties can make the call. The communication process between the two parties is the process of sending a signal to the phone and receiving a signal from the other party, which is equivalent to sending data to and receiving data from the socket. After the call ends, one party suspends the phone, which is equivalent to closing the socket and canceling the connection.

Note: The Socket can not only communicate between two computers, but also between two programs on the same computer.

4. Advanced Port (in-depth)

After a computer in the network is determined by the IP address, the computer may provide many service-providing applications, and each application corresponds to a port.

There are many such hosts on the Internet. These Hosts generally run multiple service software and provide several services. Each service opens a Socket and is bound to a port, different ports correspond to different services (applications)

For example, http uses port 80, ftp uses port 21, smtp uses port 25

5. Socket Classification

There are two main types of Socket:

Stream Socket

It is a connection-oriented Socket. It is secure but inefficient for connection-oriented TCP Service applications.

2. datagram Socket

It is a connectionless Socket, which corresponds to a connectionless UDP Service application. It is not safe but efficient.

6. General Socket Application Mode (server and client)

Server Socket (at least two)

01. One is responsible for receiving client connection requests (but is not responsible for communicating with the client)

02. Each time the client connection is successfully received, a corresponding complex communication Socket is generated on the server side.

021. created when the client connection is received

022. Create a Socket (responsible for communicating with the client) on the server for each client request that is successfully connected)

Client Socket

The server address and port to be connected must be specified.

Create a Socket object to initialize a TCP connection to the server.

We can see that the server will first create a socket for listening, then the client connects to the specified port of the server through the socket, and finally the server is responsible for listening to the socket, when the client is connected, a socket responsible for communication with the client is created.

Next let's take a look at the specific communication process of Socket:

Socket Communication Process

Server:

01. Apply for a socket

02, bound to an IP address and a port

03. Enable listening and wait for receiving the connection

Client:

01. Apply for a socket

02. Connect to the server (specifying the IP address and port number)

After the server receives the connection request, a new socket (port greater than 1024) is generated to establish a connection with the client and communicate with the client. The original listening socket continues to listen.

Note: The Socket responsible for communication cannot be created infinitely. The number of sockets created depends on the operating system.

7. Socket Constructor

Public Socket (AddressFamily addressFamily, SocketType socketType, ProtocolType protocolTYpe)

AddressFamily: Specifies the addressing scheme used by the Socket to resolve the address. For example, InterNetWork indicates that when the Socket uses an IP version 4 address to connect

SocketType: defines the type of the Socket to be opened.

The Socket class uses ProtocolType enumeration to notify Windows Sockets API of the requested protocol

Note:

1. The port number must be between 1 and 65535, preferably after 1024.

2. the remote host to be connected must be listening to the specified port, that is, you cannot connect to the remote host at will.

For example:

IPAddress addr = IPAddress. Parse ("127.0.0.1 ");

IPEndPoint endp = new IPEndPoint (addr, 9000 );

Server first Bind: serverWelcomeSocket. Bind (endp)

Client reconnection: clientSocket. Connect (endp)

3. One Socket can only connect to one host at a time.

4. the Socket cannot be used again after it is disabled.

5. Each Socket object can only be connected to one remote host. To connect to multiple remote hosts, you must create multiple Socket objects.

8. Common Socket classes and Methods

Related Classes:

IPAddress: contains an IP address.

IPEndPoint: contains a pair of IP addresses and port numbers.

Method:

Socket (): Create a Socket

Bind (): Bind a local IP address and port number (IPEndPoint)

Listen (): Let the Socket Listen to the incoming connection to take that disease, and specify the listening queue capacity

Connect (): Initialize the connection to another Socket

Accept (): receives the connection and returns a new Socket.

Send (): output data to Socket

Receive (): read data from Socket

Close (): Close the Socket and destroy the connection.

Next, let's look at Sokcet's specific usage in the case of a simple server-Client Communication:

Key code:

Server code:

Copy codeThe Code is as follows: private void Form1_Load (object sender, EventArgs e)
{
Control. checkforillegalcrossthreadcils = false;
}
Private void btnListen_Click (object sender, EventArgs e)
{
// Ip address
IPAddress ip = IPAddress. Parse (txtIP. Text );
// IPAddress ip = IPAddress. Any;
// Port number
IPEndPoint point = new IPEndPoint (ip, int. Parse (txtPort. Text ));
// Create a Socket for the listener
/*
* AddressFamily. InterNetWork: Use the IP4 address.
SocketType. Stream: supports reliable, bidirectional, and connection-based byte streams without repeated data. This type of Socket communicates with a single host and requires remote host connection before the communication starts. Stream uses the Transmission Control Protocol (Tcp) ProtocolType and InterNetworkAddressFamily.
ProtocolType. Tcp: Use the transmission control protocol.
*/
// Use IPv4 address, stream socket mode, and tcp protocol to transmit data
Socket socket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
// After creating a socket, you must tell the IP address and port number bound to the socket.
// Set the socket listening point
Try
{
// Port on which the socket listens
Socket. Bind (point );
// 10 clients are waiting in queue at the same time point
Socket. Listen (10 );
ShowMsg ("Server start listening ");
Thread thread = new Thread (AcceptInfo );
Thread. IsBackground = true;
Thread. Start (socket );
}
Catch (Exception ex)
{
ShowMsg (ex. Message );
}
}
// Record the Socket used for communication
Dictionary <string, Socket> dic = new Dictionary <string, Socket> ();
// Private Socket client;
Void AcceptInfo (object o)
{
Socket socket = o as Socket;
While (true)
{
// Communication socket
Try
{
// Create a Socket for communication
Socket tSocket = socket. Accept ();
String point = tSocket. RemoteEndPoint. ToString ();
// IPEndPoint endPoint = (IPEndPoint) client. RemoteEndPoint;
// String me = Dns. GetHostName (); // obtain the local name.
// MessageBox. Show (me );
ShowMsg (point + "connection successful! ");
CboIpPort. Items. Add (point );
Dic. Add (point, tSocket );
// Receives the message
Thread th = new Thread (ReceiveMsg );
Th. IsBackground = true;
Th. Start (tSocket );
}
Catch (Exception ex)
{
ShowMsg (ex. Message );
Break;
}
}
}
// Receives the message
Void ReceiveMsg (object o)
{
Socket client = o as Socket;
While (true)
{
// Receives the data sent from the client.
Try
{
// Define the byte array to store the data received from the client
Byte [] buffer = new byte [1024*1024];
// Put the received data into the buffer and return the length of the actually accepted data
Int n = client. Receive (buffer );
// Convert bytes into strings
String words = Encoding. UTF8.GetString (buffer, 0, n );
ShowMsg (client. RemoteEndPoint. ToString () + ":" + words );
}
Catch (Exception ex)
{
ShowMsg (ex. Message );
Break;
}
}
}
Void ShowMsg (string msg)
{
TxtLog. AppendText (msg + "\ r \ n ");
}
Private void form=formclosing (object sender, FormClosingEventArgs e)
{
// Close the subthread when the main form is closed
}
// Send a message to the client
Private void btnSend_Click (object sender, EventArgs e)
{
Try
{
ShowMsg (txtMsg. Text );
String ip = cboIpPort. Text;
Byte [] buffer = Encoding. UTF8.GetBytes (txtMsg. Text );
Dic [ip]. Send (buffer );
// Client. Send (buffer );
}
Catch (Exception ex)
{
ShowMsg (ex. Message );
}
}

Client code:
Copy codeThe Code is as follows: Socket client = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Private void btnConnection_Click (object sender, EventArgs e)
{
// Target IP address to connect
IPAddress ip = IPAddress. Parse (txtIP. Text );
// IPAddress ip = IPAddress. Any;
// Which application is connected to the target IP address (port number !)
IPEndPoint point = new IPEndPoint (ip, int. Parse (txtPort. Text ));
Try
{
// Connect to the server
Client. Connect (point );
ShowMsg ("connection successful ");
ShowMsg ("server" + client. RemoteEndPoint. ToString ());
ShowMsg ("client:" + client. LocalEndPoint. ToString ());
// After the connection is successful, you can receive the information sent by the server.
Thread th = new Thread (ReceiveMsg );
Th. IsBackground = true;
Th. Start ();
}
Catch (Exception ex)
{
ShowMsg (ex. Message );
}
}
// Receives messages from the server
Void ReceiveMsg ()
{
While (true)
{
Try
{
Byte [] buffer = new byte [1024*1024];
Int n = client. Receive (buffer );
String s = Encoding. UTF8.GetString (buffer, 0, n );
ShowMsg (client. RemoteEndPoint. ToString () + ":" + s );
}
Catch (Exception ex)
{
ShowMsg (ex. Message );
Break;
}
}
}
Void ShowMsg (string msg)
{
TxtInfo. AppendText (msg + "\ r \ n ");
}
Private void btnSend_Click (object sender, EventArgs e)
{
// The client sends messages to the server
If (client! = Null)
{
Try
{
ShowMsg (txtMsg. Text );
Byte [] buffer = Encoding. UTF8.GetBytes (txtMsg. Text );
Client. Send (buffer );
}
Catch (Exception ex)
{
ShowMsg (ex. Message );
}
}
}
Private void ClientForm_Load (object sender, EventArgs e)
{
Control. checkforillegalcrossthreadcils = false;
}

Well, here we will discuss the Socket section.

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.