Multithreading in .net Applications

zhaozj2021-02-12  150

Multithreading in .net Applications

Creating a high level of app, multithreading is a good design tool, especially those that require interoperability with users. Use Microsoft.Net easy to create such multi-threaded applications. Part1 and part2 two no part explore the NET's framework. In the first article, we discussed the background knowledge of threads, the advantages of threads, and provided examples. In the second article, we discussed the working mechanism of multi-threads, as well as thread synchronization mechanisms. In this article (the last one of multi-thread), we analyze and use system.threading, System.net.

Network programming foundation

If you write a program answering the network request, we must first understand the network composition, and the corresponding technology. I don't explain the comprehensive interpretation of the network and the network of work mechanisms. On the contrary, I will provide the basics of these topics. Some definitions are as follows:

TCP / IP - This is a set of protocols that the computer used to communicate is a routing protocol, which means if your destination owner, if it does not rely on its local network, this route will guarantee that your communication can be done.

Port-Each application based on TCP / IP protocol has a uniquely determined port. This port is a logical channel that the application is used to communicate. Some ports are reserved to protocol, such as if you connect to the web server, then you will use the 80-port, this port is HTTP reserved.

Socket-a socket is one end of the two network connections. This is a mechanism for communicating with different machines in the same machine or in the network. A socket is often bound to a specific port.

Listener Application

Listener Application is also a server program, which opens the network port while waiting for the client's connection. Such programs include web servers, database servers, e-mail servers, Chat servers, and more. Listener Application

l Generally followed the following algorithms:

l You can open the port you can use.

l You can wait for the client socket connection through the port.

l The client is connected to the Socket connection, requested a request or connection service.

l The server starts some process to send an answer.

l Turn off the client socket connection.

Sample Listener Code LISTING

The following example follows the basic algorithm mentioned above. It includes a console application that is used to open port while waiting for the customer's socket connection. Here we just write a simple connection program. Once the client is connected, the server sends the current time of the current time every few seconds to the client. This Listener then closes the connection and re-waits to other client connections.

Using system;

Using system.net;

Using system.net.sockets;

Using system.text;

Using system.threading;

Namespace codeGuru.multithreadedPart3

{

///

/// Example Console Application Demonstrating a listener / Server

/// Application.

/// Waits for Connections to Be Made and responds with a message.

///

Class HelloWorldServer

{

///

/// The main entry point for the application.

///

[Stathread]

Static void main (string [] args)

{

Try

{

Datetime now;

String datestr;

// Choose a port other than 8080 if you have differencey

TCPListener Listener = New TCPListener (ipaddress.loopback,

8080);

Listener.start ();

Console.writeLine ("Waiting for Clients To Connect");

Console.WriteLine ("Press Ctrl C To Quit ...");

While (True)

{

// Accept Blocks Until a Client Connects

Socket clientsocket = listener.acceptsocket ();

For (int i = 0; i <10; i )

{

// Get The Current Date and Time Time Build A

// Byte Array to Send

Now = datetime.now;

DateStr = now.toshortdateString () ""

now.tolongTimeString ();

Byte [] ByTedateLine = Encoding.ascii.getbytes

DateStr.ToChararray ());

// send the data

Clientsocket.send (Bytedateline, ByTedateLine.Length, 0);

Thread.sleep (1000);

Console.writeline ("Sent {0}", DateStr);

}

Clientsocket.close ();

}

}

Catch (socketexception socketex)

{

Console.WriteLine ("Socket Error: {0}", Socketex.Message;

}

}

}

}

Sample Client Code LISTING

The following code will connect the server while displaying the data sent by the server.

Using system;

Using system.io;

Using system.net;

Using system.net.sockets;

Using system.text;

Namespace codeGuru.multithreadedPart3

{

///

/// EXAMPOLE Application Demonstrating aclient

/// Application.

/// makes a connection to the server and displays the response.

///

Class HelloWorldClient

{

///

/// The main entry point for the application.

///

[Stathread]

Static void main (string [] args)

{

Bool isdone = false;

Byte [] read = new byte [32]; tcpclient client = new TCPClient ("localhost", 8080);

// Get the stream to read the input

Stream S;

Try

{

S = Client.getStream ();

}

Catch (InvalidOperationException)

{

Console.WriteLine ("Cannot Connect To Localhost";

Return;

}

// read the stream and convert it to asii

While (! isdone)

{

Int numBytes = S. Read (Read, 0, Read.Length);

String data = encoding.ascii.getstring (read);

IF (NumBytes == 0)

{

ISDONE = TRUE;

}

Else

{

Console.writeline ("received {0} bytes: {1}",

NumBytes, DATAs;

}

}

Client.Close ();

}

}

}

Testing the listener using the client

Compile the server programs and client programs to different locations, independently compile. Open the console to run the server program, and open another console to run the client program, you will see the following results.

Figure: 1-Listener

Figure 2-Client

We remit a client program again, open the third console, and perform the client program again, you will see that the two client programs only have data from the server. Another answer in the waiting server. Once the first client program is complete, the second will receive a response to the server.

Multithreaded Listener Application

The problem with the above example is that the server can only create a connection at a time. This may be enough in our Date / Time example, but for other server programs such as web servers, this is far from doing. Since the server's program is a single thread, it can only answer a client response. In order to answer multiple clients simultaneous requests. We must create different multiple threads to handle each request.

Sample Listener Code LISTING

Below is the server program in front of the code modified class, so that it should answer multiple requests at the same time. Here, we create a new thread to answer the new client request. Each client socket will be assigned to a new HelloWorldServer instance. Thus, the client request will be able to be processed by the new thread.

Using system;

Using system.net;

Using system.net.sockets;

Using system.text;

Using system.threading;

Namespace codeGuru.multithreadedPart3

{

///

/// Example Console Application Demonstrating a listener / Server

/// Application.

/// Waits for Connections to Be Made and responds with a message.

///

Class HelloWorldServer

{

// Socket To Use to Accept Client Connections

Private socket _socket; ///

/// The main entry point for the application.

///

[Stathread]

Static void main (string [] args)

{

Try

{

TCPListener Listener = New TCPListener

Ipaddress.loopback, 8080);

Listener.start ();

Console.writeLine ("Waiting for Clients To Connect");

Console.WriteLine ("Press Ctrl C To Quit ...");

While (True)

{

// Accept Blocks Until a Client Connects

HelloWorldServer HWServer = new helloworldserver ();

HWSERVER._SOCKET = listener.acceptsocket ();

// Process the Client Connection on A New Thread

Thread Samplethread = New Thread (New ThreadStart (New ThreadStart (NEW

HWServer.Process)))

Samplethread.Start ();

}

}

Catch (socketexception socketex)

{

Console.WriteLine ("Socket Error: {0}", Socketex.Message;

}

}

/ *

* Get The Current Date and Time and Send It To The Client.

* Requires That a socket is created and connection to aclient.

* Closes The socket when completion.

* /

Private void process ()

{

Datetime now;

String datestr;

For (int i = 0; i <10; i )

{

// Get The Current Date and Time Time Concatenate Build

// a byte array to send

Now = datetime.now;

DateStr = now.toshortdateString () ""

now.tolongTimeString ();

Byte [] ByTedateLine = Encoding.ascii.getbytes

DateStr.ToChararray ());

// send the data

THIS._SOCKET.SEND (ByTedateLine, BytedateLine.Length, 0);

Thread.sleep (1000);

Console.writeline ("Sent {0}", DateStr);

}

THIS._SOCKET.CLOSE ();

}

}

}

Testing The Multithreaded Listener Using The Client

Copy updated server program code to the appropriate location and recompile. Run the server program from the console. Run multiple client programs from multiple different console, you will notice that both client programs can receive the response of the server.

Possible Enhancements

The above example includes a simple server program and client program that you can use as the beginning of the SYSTEM.NET name space. In addition, you can do the following extension: extend the client program to send a specific work request. Change server programs to answer different specific work requests. E.g:

l The client can send "DataTime" data as a request, while the server responds with Date and Time.

l Do not use the console as a server, and use the Windows server so that you can start automatically, and run in the background.

About the Author

Mark Strawmyer, MCSD, MCSE (NT4 / W2K), MCDBA is a Senior Architect of .NET applications for large- and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in the architecture, design And development of microsoft-based solutions. You can Reach mark at mstrawmyer@crowechizek.com.

转载请注明原文地址:https://www.9cbs.com/read-6217.html

New Post(0)