C # socket programming (5) use TCP socket

Source: Internet
Author: User
Tags getstream

TCP protocol(Transmission control protocol, transfer control protocol) isConnection oriented transmission layer in TCP/IP System),TCP protocolIt can detect and recover possible packet loss, duplication, and other errors from the host to the Host channel provided by the IP layer. TCP is a connection-oriented protocol: before using it for communication, two applicationsProgramFirst, establish a TCP connection. TCP can provide duplex and reliable services in the network.

Reading directory:

1. TCP Overview

2. Working Mode of TCP applications on the. NET platform

2.1 understand tcplistener and tcpclient

3. Solve the message borderless problem of TCP

3.1 send a fixed-length message

3.2 send the message length together with the message

3.3 use special tags to separate messages

4. Example of synchronous TCP socket

5. Download sample source code

6. Further reading and reference

1. TCP Overview

After both parties establish a TCP connection, both parties can send data to each other. TCP is responsible for sending user data (byte streams) into multiple datagram data sets according to a certain format and length, and then re-assemble and restore user data in order after receiving the datagram.Data is transmitted in bytes when data is transmitted over TCP. After the client establishes a connection with the server, the sender must first convert the data to a byte stream, and then send the byte stream to the other party. TCP has the following features:

  1. Is a connection-oriented transport layer protocol.
  2. Each TCP connection can have only two endpoints and only one-to-one communication
  3. Data transmission over TCP connections ensures the integrity and accuracy of packets.
  4. Data can only be transmitted in byte streams
  5. The transmitted data has no message boundaries.

 

2. Working Mode of TCP applications on the. NET platform

Develop TCP applications on the. NET platform. The framework provides two working methods,① Synchronous mode ② asynchronous mode. The synchronous mode and asynchronous mode and the synchronization between threads are not a concept. Synchronization between threads refers to the relationship between different threads or other shared resources. synchronous TCP and asynchronous TCP refer to the two different working modes used in TCP programming, that is, whether the program continues to execute the statements from execution to method, receipt, or listening,Asynchronous TCP continues to be executed. If the program is blocked, synchronous TCP is used..

In response to the synchronous and asynchronous modes of work, the. NET Framework for application development using Socket classes also provides the corresponding programming methods:Synchronous socket programmingAndAsynchronous socket programming. To simplify programming complexity,. Net further encapsulates socket classes and provides two classes:TcpclientClass andTcplistenerThe two classes also provide APIs for synchronous and asynchronous operation.

2.1 understand tcplistener and tcpclient

We know from the above:TcpclientClass andTcplistenerClass simplifies the complexity of socket programming, but note the following:TcpclientAndTcplistenerThese two classes only support standard protocol programming. If you need to write non-standard protocol applications, you can only useSocket.

TcpclientClass is used to provide the connection information between the local host and the remote host, whileTcplistenerThe class is used to listen to client requests (for more information about these two classes, refer to the msdn class library. The connection has been provided in this article and will not be described here ). After a connection is established for the socket communication, a tcpclient object is created, you can useGetstream ()MethodNetworkstreamAnd then use the network stream object to send or receive streaming data to the remote host.

 

3. Solve the Problem of no message boundary of TCP

We know that network data transmission is stream-based. TCP communication ensures the order and integrity of data received and sent, however, in the actual network transmission process, the sender and receiver messages may be inconsistent. For example, if the data sent for the first time is "123456" and the data sent for the second time is "abcdef", this may happen sometimes: "123456abcdef" is received at the same time; or, you can receive "123456abc" and then "def. This is because:TCP is a message-free protocol transmitted in byte streams. Due to the influence of uncertain factors in the network, it cannot ensure that the data sent by each send method is read by the corresponding recive.. So in actualThe message boundary must be considered for Socket Application Development.Otherwise, data errors may occur. The following three methods are generally used to solve TCP Message boundary. We can select different methods based on different scenarios.

3.1 send a fixed-length message

This method is applicable to scenarios with fixed message lengths. You can useBinaryreader/binarywriteR object streams to the network each time,Send/readA fixed length of data. For example, a 32-bit integer of the int type is sent each time.

1Tcpclient client =NewTcpclient ("Www.baidu.com",5968);2Networkstream m_netstream =Client. getstream ();3Binarywriter BW =NewBinarywriter (m_netstream, encoding. utf8 );4Bw. Write (99);

 

3.2 send the message length together with the message

This method is generally used to display the length of the message in four bytes before each message is sent, and then the message containing the message length is sent to the other party. After the other party receives the message, first, read the message length from the first four bytes of the message, and then receive the data sent by the sender Based on the message length value. This method is applicable to any scenario where we can useBinaryreaderAndBinarywriterObjectNetworkstreamFurther encapsulation, when we useBinarywriterObject callWrite (+ 18 overload)When writing data to a network stream, this method automatically calculates the number of bytes used for sending data, and appends four (based on the data type sent) bytes to the front of the string. Then the other party usesBinaryreaderObjectCorresponding to binarywriterWhen the write () method of the object reads data, it first reads the length of the data and automatically reads the data of the specified length based on the data prefix.

 

3.3 use special tags to separate messages

This method is applicable when messages do not contain special tags. For example, add the line break (\ r \ n) symbol to the end of each command as the separator. For string processing, the easiest way to implement this method is to useStreamwriterObject andStreamreaderObject. Used for sendingStreamwriterThe writeline () method of the object writes the sent string to the network stream. The receiver only needs to callStreamreaderThe Readline () method of the object reads the string using the carriage return linefeed as the separator from the network stream.

 

4. Sample TCP socket synchronization Program

After the accumulation of previous knowledge, we can directly create a simple chat program based onSynchronous TCP socketThe implementation of Web chat programs and programs is relatively simple. The server receives connections from multiple clients, and the client communicate with each other directly through the server. Direct Message interaction between the client and the serverJSONThe third-party JSON library is used here.JSON. net(For details about JSON. Net Usage, refer:Summary of JSON. Net Usage). The following figure shows the effect of running the program:

Run the server:

Open multiple clients, select a chat object in the online list, and send chat information:

 

Example source code: Click to download

References & further reading

Wikipedia: Transmission Control Protocol (TCP)

C # network application programming 2

Author:Sunny pig

Source:Http://www.cnblogs.com/IPrograming

The copyright of this article is shared by the author and the blog. You are welcome to repost it and indicate the source.

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.