The examples in the previous topic are based on the HTTP protocol at the application layer. Now we will introduce the transport layer protocol-TCP protocol, this article mainly introduces the working process of TCP protocol and a simple communication program based on TCP protocol.
1. TCP Workflow
TCP is a connection-oriented, reliable, and byte stream-based transport layer communication protocol. The TCP process can be divided into three stages: 1. Connection establishment; 2. Data Transmission; 3. Disconnection. The following describes the three processes respectively:
1.1 establish a connection
The establishment of a TCP connection is like making a call. When we call a phone, the number of a number cannot be connected immediately. During this call, there will be a "beep" Call process, this is like the establishment of a TCP connection. When we use a program written in TCP, we must first establish a TCP connection. TCP connections are established through three-way handshakes. The following figure shows a TCP three-way handshakes on the Internet:
Here is a brief introduction to these three handshakes:
First handshake: when a connection is established, the client sends the SYN Packet (SEQ = x) to the server and enters the syn_send status. Wait for the server to confirm.
The second handshake: when the server receives the SYN packet, it must confirm the customer's Syn (ACK = x + 1) and send a SYN Packet (SEQ = Y), that is, SYN + ACK packet, the server enters the syn_recv status.
The third handshake: the client receives the server's SYN + ACK package and sends the ACK (ACK = Y + 1) Confirmation package to the server. After the package is sent, the client and server enter established (created) status, complete three handshakes.
A simple understanding of three handshakes is to send a test packet to the other party and then confirm each other. when both parties receive a confirmation signal, the two sides establish a connection (like when we call, if no one is talking, he will say "hello" and say "hello", that is, he hopes to get confirmation from the other party. Although the two parties have established a connection, here is a more vivid description of the three-way handshake process ).
1.2 Data Transmission
The two sides establish a connection, that is, a communication channel is established between the two sides (just like a bridge, a channel is established at both ends, the bridge is used to compare the communication channel mainly because of the recent news: the collapse of the yangmingtan Bridge in Harbin). After the connection is established, of course, the data we need to transmit to the other party is transmitted, here we will start a brief introduction to the data transmission process.
When data is transmitted over TCP, the data is transmitted in the form of a byte stream. After the client establishes a connection with the server, the sender must first convert the sent data to a byte stream, then, send the data to the other party. When sending the data, the program can continuously write the data stream into the TCP sending buffer, and then TCP automatically extracts a certain amount of data from the sending buffer, sends a TCP packet segment to the IP layer, and then sends it through the network interface under the IP layer (that is, the network layer). After the receiver receives the TCP packet segment from the IP layer, save it in the accept buffer temporarily, and then we read the data in the accept buffer in sequence through the program to achieve the purpose of mutual communication (simply put, the sender converts the data into a data stream, store the data stream in the sending buffer, and then the protocol at the transport layer reads data from the sending buffer to send the data, then, the receiver receives data from the underlying layer and stores the data in the buffer of the receiver. Then, the program we write reads data from the buffer in sequence and then displays the data, on the client side, we write code to write the data into the buffer of the sending end, and then the server side (the receiving end) uses the read method in itself. Read data in the buffer, in one sentence, TCP transmission is the write-read operation of data.) The content in the brackets is only my personal understanding, because it makes me feel easier to understand, for friends who are new to TCP, they can understand this and extend it with just one sentence.
1.3 disconnect
After the data is sent, the connection is disconnected. Below is a picture of the disconnected connection from the Internet (the disconnection requires four handshakes)
The TCP work process is divided into the above three processes. TCP programming is the basis for upper-layer application programming, just as in the previous topic, the HTTP-based Web server, web browser, the transmission layer uses the TCP protocol for transmission, as well as FTP (file transfer protocol) and IMAP (Interactive mail access protocol) POP3 (3rd Post Office Protocol versions) for network applications of SMTP (Simple Mail Transfer Protocol), the transport layer uses TCP rather than UDP and other transport layer protocols.
2. Simple communication program based on TCP protocol
Here is a simple communication program between the client and the server. The core code is:
Client Connection server code:
Private void btnconnect_click (Object sender, eventargs e) {// initiate a request through a thread, multithreading thread connectthread = new thread (connecttoserver); connectthread. start () ;}// Method for connecting to the server. The connection process is private void connecttoserver () {try {// call the delegate statusstripinfo. invoke (showstatuscallback, "Connecting... "); If (tbxserverip. TEXT = string. empty | tbxport. TEXT = string. empty) {MessageBox. show ("Enter the Server IP address and port number first");} IPaddress iPad Dress = IPaddress. parse (tbxserverip. text); tcpclient = new tcpclient (); tcpclient. connect (IPaddress, Int. parse (tbxport. text); // delay operation thread. sleep (1000); If (tcpclient! = NULL) {statusstripinfo. invoke (showstatuscallback, "connection successful"); networkstream = tcpclient. getstream (); reader = new binaryreader (networkstream); writer = new binarywriter (networkstream);} catch {statusstripinfo. invoke (showstatuscallback, "connection failed"); thread. sleep (1000); statusstripinfo. invoke (showstatuscallback, "ready ");}}
Code for sending a message from the client:
// Send the message private void btnsend_click (Object sender, eventargs e) {thread sendthread = new thread (sendmessage); sendthread. start (tbxmessage. text);} private void sendmessage (object state) {statusstripinfo. invoke (showstatuscallback, "sending... "); try {writer. write (state. tostring (); thread. sleep (5000); writer. flush (); statusstripinfo. invoke (showstatuscallback, "finished"); tbxmessage. invoke (resetmessagecall Back, null); lstbxmessageview. Invoke (showmessagecallback, state. tostring ();} catch {If (reader! = NULL) {reader. Close () ;}if (writer! = NULL) {writer. Close () ;}if (tcpclient! = NULL) {tcpclient. Close ();} statusstripinfo. Invoke (showstatuscallback, "disconnected ");}}
The server accepts the code to start listening to client requests:
// Start listening to private void btnstart_click (Object sender, eventargs e) {tcplister = new tcplistener (IPaddress, Port); tcplister. start (); // start a thread to accept the request thread acceptthread = new thread (acceptclientconnect); acceptthread. start () ;}// accept the request private void acceptclientconnect () {statusstripinfo. invoke (showstatuscallback, "listening"); thread. sleep (1000); try {statusstripinfo. invoke (showstatuscallback, "waiting for connection"); tcpcl Ient = tcplister. accepttcpclient (); If (tcplister! = NULL) {statusstripinfo. invoke (showstatuscallback, "Connect accepted"); networkstream = tcpclient. getstream (); reader = new binaryreader (networkstream); writer = new binarywriter (networkstream);} catch {statusstripinfo. invoke (showstatuscallback, "Stop listening"); thread. sleep (1000); statusstripinfo. invoke (showstatuscallback, "ready ");}}
Now let's look at the running results:
Start the server first and then start listening. At this time, the thread will be blocked until a connection request is received.
Run the client, enter the IP address and port number of the server at the IP address and port, and click the connect server button. The interface is as follows:
You can use the accept button and send button to communicate with each other. The implementation interface is as follows:
Iii. Summary
The content of this topic is almost the same here. This topic mainly introduces the TCP-based working process and custom a simple communication program on the net platform, I hope this topic will help some friends who are new to the TCP protocol (you should be able to flash it). I will share with you about UDP programming in the following topics, after UDP programming, We will combine the content of these two chapters to implement a tool similar to QQ instant chat. I hope these tools will be helpful to everyone, if you have any questions or want to know about the topics you are interested in, you can leave me a message and share it with you in subsequent articles.
I feel that I am recommended to anyone who can help me after reading this article and give me the motivation to continue. If you have any topics of interest, I can leave a message to tell me, I will share it with you one after another.
The source code of this program is as follows:
Http://files.cnblogs.com/zhili/%E7% AE %80%E5%8D%95%E9%80%9A%E4%BF%A1%E7%A8%8B%E5%BA%8F.zip
Link: http://www.cnblogs.com/zhili/archive/2012/08/25/TCP.html