. Net 4.0 getting started with network development 7 -- fill in the buffer trap

Source: Internet
Author: User

Getting started with. Net 4.0 network development --


Fill buffer traps


Note:


This is
Beginners in the Network Development Field
A series of articles, which can be used as an introduction to. Net 4.0 Object-Oriented Programming



The expanded reading of this book. During the writing process, I assume that the reader can read the relevant chapters of this book without wasting any effort to introduce the relevant content.


For other types of readers, unless you have the corresponding. Net technical background and certain development experience, you may encounter difficulties in reading.


I hope this series of articles will give readers a taste of the charm of network development!


In addition, these articles are original articles. Please respect the work of the author. I allow everyone to freely repost these articles and related examples for the purpose of knowledge sharing, but without my permission, please do not use it for commercial profit purposes.

If any error occurs in this article, please reply and correct it.


Thank you!

 


Jin xuliang

========================================================== ==========

Click the following link to read the previous articles in this series:

 

1 《

Opening Speech --
Invincible


2 《
IP address knowledge

3. I am in the center of "network"
"

4 "first appointment with socket"
"

5 "meet again" with socket"
"

6 "troublesome" Data Buffer
"

========================================================== =

The buffer zone in the previous article "causing trouble"
This section introduces two issues that must be paid attention to when programming the data buffer zone of TCP socket:
(1) TCP does not save the boundary of a message. Therefore, the server must be able to correctly split a complete message from the received data.
(2) The sending and receiving rates of data from the client and the server must match. Otherwise, "Sticky packets" and "packet loss" may occur.
So how can we solve these two problems?
1 indicates the uniform length of multiple messages to be transmitted


This is the most intuitive method. We can create a message code table in advance. Each message code represents a different meaning. For example, "000" represents "initialization ", "999" indicates "end" and so on. This idea can also be seen in HTTP. For example, HTTP defines some status codes. 200 indicates "OK ", 500 indicates "internal server error ". You can also refer to the design method of CPU instructions to develop some fixed-length "message code table ".
Because all messages have the same length, the processing on the server will become very simple. It just needs to cut the received data according to the agreed length.
See the sample solution fixedsizemessagedemo. The client needs to send an int array to the server. The server uses a memorystream to store the data, and then reads the data in four bytes to restore the data correctly.
The following is the server code framework:

Int Recv = 0;
// Memory stream used for temporary data storage
Memorystream mem = new memorystream ();
While (true) // receives all data from the client
{
// Save the received data to the memory stream
Recv = client. Receive (data );
Mem. Write (data, 0, Recv );
If (Recv = 0) // The client {0} is disconnected after receiving the data
{
Client. Close ();
Break;
}
}
Mem. Seek (0, seekorigin. Begin );
Long datalength = mem. length;
Binaryreader reader = new binaryreader (MEM );
Console. writeline ("received data :");
While (reader. basestream. Position <datalength)
{
// Split data
Console. Write ("{0},", reader.Readint32 ()

);
}
Reader. Close ();

2. append message length information


Although using a fixed-length message can simplify the code on the server, it is quite limited. It is also troublesome to design a complete set of message code.
A better way is to combine the two, and append a fixed-length "message length" information at the beginning of each message, so that the server knows how long the message actually exists.
This is exactly what the HTTP protocol does. There is a Content-Length entry in the header of the HTTP Response Message (headers) to notify the browser of the number of bytes of the body of the HTTP message.

Tip:
HTTP is an application layer protocol that relies on the TCP protocol to transmit HTTP messages at the underlying layer.

First, we design a static method for sending data:

// Send variable-length data and append the data length to the beginning of the data
Public static int sendvardata (socket S, byte [] data)
{
Int Total = 0;
Int size = data. length; // message length to be sent
Int dataleft = size; // remaining messages
Int sent;
// Convert the message length (INT type) to a byte array
Byte [] datasize = new byte [4];
Datasize = bitconverter. getbytes (size );
// Send the message length
Sent = S. Send (datasize );
// The remaining part of the sent message
While (total <size)
{
Sent = S. Send (data, total, dataleft, socketflags. None );
Total + = sent;
Dataleft-= sent;
}
Return total;
}

Taking a closer look at the comments, the work completed by the above code is "clear at a glance" and there is no need to talk nonsense.
The following static methods are used to receive and split messages:

// Receives variable-length data and requires that the four bytes indicate the length of valid data.
Public static byte [] incluevardata (socket S)
{
If (S = NULL)
Throw new argumentnullexception ("S ");
Int Total = 0; // number of received bytes
Int Recv;
// Receives 4 bytes to get the message length"
Byte [] datasize = new byte [4];
Recv = S. Receive (datasize, 0, 4, 0 );
Int size = bitconverter. toint32 (datasize, 0 );
// Receive data by message length
Int dataleft = size;
Byte [] DATA = new byte [size];
While (total <size)
{
Recv = S. Receive (data, total, dataleft, 0 );
If (Recv = 0)
{
Break;
}
Total + = Recv;
Dataleft-= Recv;
}
Return data;
}

As you can see, because the message length is known "in advance", receiving messages becomes very intuitive.
To facilitate reuse, we can put the above two static methods into a static class sockethelper and add this class to the mynetworklibrary class library. These two methods will be used in future examples.
The sample solution variablelengthmessagedemo shows how to use the preceding method to send variable-length data.
3. "One question and one answer" Data Transmission


By carefully analyzing the TCP protocol, we will find that it achieves reliable data transmission through the "handshake" of "one question and one answer.
We can achieve "one-question-one-answer" communication at a higher level based on Huludao. Simply put:


After the data sender sends a message, it stops waiting for the receiver to send a confirmation message. After receiving the message, it sends the second message.
Since the data recipient knows exactly that the sender only sends one message at a time, it can "safely and boldly" continue to receive data until the receive method returns 0. Then, then, send a "notification" of "received message" to the sender, and then prepare to receive the Next message.


For this type of data communication, each message does not have to be attached with length information.
See the sample solution sendandwaitdemo. After the client sends the data, it sends a "sendfinished" message. After receiving the data, the server sends a "receivefinished" message. The client will not send new messages if it does not receive the "receivefinished" message.
Please read the source code on your own and do not go into details.


4. Develop a "Network calculator"


Many examples are designed for the purpose of learning and have almost no practical use. After learning so much about socket programming knowledge, we finally have the premise to develop a "a little usable" network application.
In 《. the 4.0 chapter in the net 24th object-oriented programming book introduces a "Four arithmetic calculators" that support addition, subtraction, multiplication, division, and multi-level brackets ", in addition, the related pre-order and mid-order expression parsing algorithms are encapsulated into an assembly mathfunclib. DLL. By reusing this Assembly and adding the new socket programming technology, we can implement a "network-based arithmetic calculator" (networkcalculator ).



Figure 1

In the preceding example, the client uses the sendvardata method described earlier to send an expression and uses the evardata method to receive the computation results sent back by the server. The server uses the medium-order algorithm parsing expression encapsulated by the mathfunclib Assembly. Its expressions receive and return the calculation results using the evardata and sendvardata methods.
Please read the source code by yourself.


Finally, leave a few homework:
Apply ". Net 4.0 object-oriented programming" to readers
The multi-thread technology introduced in, transforming the networkcalculator sample program:
(1) allows the server to respond to expressions of multiple clients simultaneously to compute requests
(2) Change the client from the console program to Windows Forms or WPF program, and start the thread in the background to send and receive expressions and calculation results.

Next, it is difficult:

To improve processing efficiency, allow the client to package multiple expressions to be calculated and send them together to the server. After the server completes computing, then, all the results are packaged and sent back to the client at a time.
With the technology introduced in this article, can you develop such a program?
In the next lecture, We will "Say goodbye" to TCP for the time being, and take a look at another very important protocol-udp!

========================================================== ========================================================
For more information about the example program of "Four arithmetic calculators" and mathfunclib. dll, see. Net 4.0 Object-Oriented Programming
In chapter 1 of the book, readers can find the download link from the book's supporting resource package. The download links in the csdn download channel are listed below:

Text and source code from object-oriented to SOA
Http://download.csdn.net/source/2739426)

The following is the download link of the sample source code appended to this article:

 

Download sample source code


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.