Using the basic class library--ZT Unified Teaching Network

Source: Internet
Author: User
Tags constructor connect variables thread client
Using the base Class library


To better understand the difference between C # and C + + and how to solve the problem, let's look at a simpler example. We will create a class that reads the text file and display its contents on the screen. I'll make it into a multithreaded program so that I can do other things when I read data from disk.

In C + +, we might create a thread that reads files and another thread that does other work, and these two threads will run independently, but they may need to be synchronized. In C #, we can do the same work, because. NET Framework provides powerful asynchronous I/O mechanisms, and we save a lot of time writing threads.

asynchronous I/O support is built into the CLR and is almost as simple as using a normal I/O stream class. At the beginning of the program, we first inform the compiler that we will use the objects in many namespaces in the program:

Usingsystem;
Usingsystem.io;
Usingsystem.text;

Contains system in a program and does not automatically contain all of its child namespaces, and must explicitly contain each child namespace using a using key word. We use the I/O stream class in the example, so we need to include the System.IO namespace, and we also need the System.Text namespace to support the ASCII encoding of the byte stream.

Because. NET architecture to do most of the work, the steps required to write this program are fairly straightforward. We will use the BeginRead method of the Stream class, which provides asynchronous I/O capabilities, reads data into a buffer, and invokes the corresponding handler when the buffer is ready to be processed.

We need to use a byte array as the proxy for the buffer and callback methods, and define the two as private member variables for the driver class.

Publicclassasynchiotester
{
Privatestreaminputstream;
Privatebyte[]buffer;
Privateasynccallbackmycallback;

InputStream is a variable of the stream type, and we will call the BeginRead method on it. The proxy is very similar to the pointer to a member function. The agent is the first type of element in C #.

When the buffer is filled with the file on the disk. NET will invoke the method of the proxy to process the data. While waiting to read the data, we can get the computer to do other work. (In this case, 1 integer variables are increased from 1 to 50000, but in a real application, we can have the computer interact with the user or do other meaningful work.) )

The proxy in this example is defined as the AsyncCallback type process, which is required by the BeginRead method of the stream. The definition of the AsyncCallback type Proxy in the system space is as follows:

Publicdelegatevoidasynccallback (Iasyncresultar);

This agent can be associated with any method that returns a void type value and takes the IAsyncResult interface as a parameter. When the method is invoked, the CLR can pass the IAsyncResult interface object as a parameter at run time. We need to define this method in the form shown below:

Voidoncompletedread (Iasyncresultasyncresult)

Then connect to the agent in the constructor:

Asynchiotester ()
{
???
Mycallback=newasynccallback (this. Oncompletedread);
}

The above code assigns an instance of the proxy to the member variable Mycallback. Here is the detailed working principle of all programs. In the main function, you create an instance of a class and let it start running:

Publicstaticvoidmain ()
{
Asynchiotestertheapp=newasynchiotester ();
Theapp.run ();
}

The New keyword can start the constructor. In the constructor we open a file and get a stream object. It then allocates space in the buffer and joins it with the callback mechanism.

Asynchiotester ()
{
Inputstream=file.openread (@ "C:\MSDN\fromCppToCS.txt");
Buffer=newbyte[buffer_size];
Mycallback=newasynccallback (this. Oncompletedread);
}

In the Run method, we call BeginRead, which reads the file asynchronously.

Inputstream.beginread (
buffer,//Storage Results
0,//Offset
Buffer. How many bytes are in the length,//buffer
mycallback,//Callback Agent
NULL);//local Object

At this point, we can do other work.

for (longi=0;i<50000;i++)
{
if (i%1000==0)
{
Console.WriteLine ("I:{0}", i);
}
}

After the file read operation is complete, the CLR invokes the callback method.

Voidoncompletedread (Iasyncresultasyncresult)
{

The first thing to do in Oncompletedread is to find out how many bytes were read by calling the EndRead method of the Stream object:

Intbytesread=inputstream.endread (asyncresult);

The call to EndRead returns the number of bytes read. If the number returned is greater than 0, the buffer is converted to a string, then written to the console, and then called again BeginRead to start another asynchronous read process.

if (bytesread>0)
{
Strings=encoding.ascii.getstring (Buffer,0,bytesread);
Console.WriteLine (s);
Inputstream.beginread (Buffer,0,buffer. Length,
Mycallback,null);
}

Now you can do something else while reading the file (in this case from 1 to 50000), but we can process the read data each time the buffer is full (in this case, the data in the console output buffer). Interested readers can click here to download the complete source code.

The administration of asynchronous I/O is entirely provided by the CLR, so that it is better to read files on the network.



Read files on the network


In C + +, it requires considerable programming skills to read files on the network. NET provides a wide range of support for this. In fact, reading files on a network is just another application of the stream class in the underlying class library.

First, to monitor the TCP/IP port (65000 in this case), we need to create an instance of the TcpListener class.

Tcplistenertcplistener=newtcplistener (65000);

Once created, let it begin to listen.

Tcplistener.start ();

Now it's time to wait for the customer to connect.

Socketsocketforclient=tcplistener.accept ();

The Accept method of the TcpListener object returns a socket object, accept is a synchronized method that is returned only if a connection request is received. If the connection is successful, you can start sending the file to the customer.

if (socketforclient.connected)
{
???


Next, we need to create a NetworkStream class that passes the report to constructor:

Networkstreamnetworkstream=newnetworkstream (socketforclient);

Then create a StreamWriter object, just this time not on the file but on the NetworkStream class that you just created:

System.io.streamwriterstreamwriter=
NewSystem.IO.StreamWriter (NetworkStream);

When writing content to this stream, the stream is transmitted over the network to the client.



Client-side Creation


The client software is a specific example of a TcpClient class, where the TcpClient class represents a TCP/IP connection to the host.

Tcpclientsocketforserver;
Socketforserver=newtcpclient ("LocalHost", 65000);

With the TcpClient object, we can create the NetworkStream object and then create the StreamReader class on it:

Networkstreamnetworkstream=socketforserver.getstream ();
System.io.streamreaderstreamreader=
NewSystem.IO.StreamReader (NetworkStream);

Now, as long as the data is enrolled in the stream, the results are exported to the console.

Todo
{
Outputstring=streamreader.readline ();

if (outputstring!=null)
{
Console.WriteLine (outputstring);
}
}
while (Outputstring!=null);

To test this piece of code, you can create one of the following test files:

Thisislineone
Thisislinetwo
Thisislinethree
Thisislinefour

This is the output from the server:

Output (Server)
clientconnected
Sendingthisislineone
Sendingthisislinetwo
Sendingthisislinethree
Sendingthisislinefour
Disconnectingfromclient ...
Exiting ...

The following is the output from the client:

Thisislineone
Thisislinetwo
Thisislinethree
Thisislinefour



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.