C # network programming (asynchronous transmission of strings) iii

Source: Internet
Author: User

In this article, we will take a big step forward by programming the server in asynchronous mode to make it a real server: Multiple client requests can be processed. But before we start, we need to solve a problem left over from the previous section.

Message sending Problems

This problem is: when the client writes data (such as a string) to the stream twice, we regard the two writes as two requests; however, the server may regard these two requests as one request, especially when the two requests have a short interval. Likewise, a client may send a request, but the server treats it as two requests. The following lists the possible cases. Suppose we send two "Welcome to Tracefact.net!" consecutively on the client !", When the data arrives at the server, there may be three situations:

NOTE:Here we assume that the ASCII encoding is used, because the box above exactly represents a byte, and the string reaches the end with a continuous 0 (because byte is a value type, and the minimum value is 0 ).

The first case above is the ideal situation. At this time, the two messages are regarded as two independent requests completely received by the server. In the second case, a message is received as two messages:

In the third case, the two messages are merged into one receiver:

If you download the source code included in the previous article, modify Client2.cs and send three requests consecutively using a for loop instead of user input, this will shorten the request interval. The following is the key code:

String msg = "Welcome to TraceFact. Net! ";

For (int I = 0; I <= 2; I ++ ){
Byte [] buffer = Encoding. Unicode. GetBytes (msg); // obtain the cache
Try {
StreamToServer. Write (buffer, 0, buffer. Length); // send to the server
Console. WriteLine ("Sent: {0}", msg );
} Catch (Exception ex ){
Console. WriteLine (ex. Message );
Break;
}
}

Run the server and then run the client. You may see the following results:

As you can see, although the message is divided into three separate messages, the server merges the last two messages into one. We can handle these situations as follows: Just like the HTTP protocol, the actual request and response content contains the HTTP header, some of which are request-related information. We can also establish our own agreement to solve this problem. For example, for the above situation, we can define such an agreement:

[Length = XXX]: Where xxx is the actual length of the sent string (note that it is not the length of the byte array buffer), then for the above request, the data we send is: "[length = 25] Welcome to TraceFact. net! ". After receiving the string, the server first reads the "metadata" content and then reads the actual data based on the "metadata" content. There are two possible situations:

NOTE:I think it is more appropriate to use the term "metadata" here, because "metadata" is used to describe data.

  • The brackets in "["] "are complete and can read the number of bytes of length. Then, based on this value, if it is equal to the length of the subsequent string, it indicates that a complete message is sent. If it is more, it indicates that the number of received bytes is large and the appropriate length is obtained, and cache the remaining items. If it is missing, it indicates that the received items are insufficient. Then, cache the received items, wait for the next request, and merge the two items.
  • [""] "Brackets are incomplete. At this time, the length value cannot be read. Because the content in the brackets is truncated, the read data is cached, wait for the data to be read next time, and then merge the data twice before processing the data as shown above.

Next, let's take a look at how to perform actual operations. In fact, this issue is not part of the C # network programming content, but is completely about string processing. Therefore, we no longer need to write server/client code, but directly write methods to handle these situations:

Public class RequestHandler {
Private string temp = string. Empty;

Public string [] GetActualString (string input ){
Return GetActualString (input, null );
}

Private string [] GetActualString (string input, List <string> outputList ){
If (outputList = null)
OutputList = new List <string> ();

If (! String. IsNullOrEmpty (temp ))
Input = temp + input;

String output = "";
String pattern = @"(? <= ^ [Length =) (d + )(? =]) ";
Int length;

If (Regex. IsMatch (input, pattern )){

Match m = Regex. Match (input, pattern );

// Obtain the actual length of the message string
Length = Convert. ToInt32 (m. Groups [0]. Value );

// Obtain the position to be intercepted
Int startIndex = input. IndexOf (]) + 1;

// Obtain the length of all characters starting from this position
Output = input. Substring (startIndex );

If (output. Length = length ){

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.