[C # network programming series] Topic 5: TCP Programming

Source: Internet
Author: User
Tags getstream file transfer protocol

Preface

 

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 the TCP protocol and a simple communication based on the TCP protocol.ProgramNext, we will start the text of this topic.

 

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 the data from the underlying layer and stores the data in the buffer of the receiver. Then, the program we write reads the data from the buffer in sequence and then displays the data.CodeThe task is to write the data into the buffer of the sending end, and then the server (acceptor) reads the data in its own buffer using the read method. In a word, TCP transmission is the write-read operation of data.) The content in the brackets is only my personal understanding, because it is easier for me to understand, and can be understood by friends who are new to TCP, then, let's extend it in a sentence.

1.3 disconnect

After the data is sent, the connection is disconnected. The following figure shows a picture of the disconnected connection on the Internet (four handshakes are required to disconnect the connection ):

 

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 using one thread and multiple threads Thread connectthread = New  Thread (connecttoserver); connectthread. Start ();}  //  Connection to the server          Private   Void  Connecttoserver (){  Try  { //  Call delegate Statusstripinfo. Invoke (showstatuscallback, "  Connecting...  "  );  If (Tbxserverip. Text = String . Empty | tbxport. Text = String  . Empty) {MessageBox. Show (  "  Enter the IP address and port number of the server.  "  );} IPaddress = IPaddress. parse (tbxserverip. Text); tcpclient = New  Tcpclient (); tcpclient. Connect (IPaddress,  Int . Parse (tbxport. Text ));  //  Delayed 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 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 (resetmessagecallback,  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          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 request          Private   Void  Acceptclientconnect () {statusstripinfo. Invoke (showstatuscallback,  "  Listening  "  ); Thread. Sleep (  1000  );  Try  {Statusstripinfo. Invoke (showstatuscallback,  "  Waiting for connection  "  ); Tcpclient = Tcplister. accepttcpclient ();  If (Tcplister! = Null  ) {Statusstripinfo. Invoke (showstatuscallback, "  Accept connection  "  ); 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 more about the topics, you can leave a message for me.ArticleWe will share it with you.

 

 

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.

Below is the programSource code:

http://files.cnblogs.com/zhili/%E7% AE %80%E5%8D%95%E9%80%9A%E4%BF%A1%E7%A8%8B%E5%BA%8F.zip

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.