Use Visual C # To implement P2P applications

Source: Internet
Author: User
Tags case statement switch case

I. Preface:

P2P, short for peer-to-peer, is translated as peer-to-peer technology. When it comes to P2P, people will think of Napster. Napster makes people realize the power of P2P technology, and the P2P technology enters the vision of most users through Napster, napster's music file exchange function is a main application of P2P. P2P technology allows users to directly connect to other users' computers for file sharing and exchange. P2P is also useful in Deep Search, distributed computing, and collaborative work.

To put it simply, P2P is a technology used to directly exchange data or services between users in different PCs without passing through relay devices. It allows Internet users to directly use the files of the other party. Each user can directly connect to another user's computer and exchange files without having to connect to the server for browsing and downloading. Because intermediate links are eliminated, P2P technology makes communication on the network easier and more direct. P2P changes the current state of the Internet centered on large websites, returns to "non-central", and returns power to users. In a sense, P2P reflects the essence of the Internet. Before the network has evolved into the current web, netizens directly exchange information and files through the so-called "bulletin board" and other channels.

Currently, the Internet storage mode is "content in the center", and the application of P2P technology will move content on the Internet to the edge. This will bring about the following changes: first, the customer no longer needs to upload files to the server, but only needs to share the files with other computers using P2P. Second, computers using P2P technology do not need a fixed IP address or a permanent internet connection. This allows a large proportion of dial-up Internet users to enjoy the revolution brought about by P2P.

The best way to understand P2P technology is to carefully observe and understand a practical P2P application.Program. As an important part of Microsoft's. NET strategy, C # provides excellent support and Optimization for network programming. This article introduces the P2P programming method and implementation mechanism under C # through a program. Although this program in this article is not very useful, it intuitively provides some basic knowledge and concepts of P2P (point-to-point) programming and set interface programming. It is based on tcplistener and tcpclient, except for corresponding Input and Output Control. The implementation principle is also relatively simple, but the basic principle of returning P2P technology to "non-central" is used. In short, this program can send and receive information on the network. Any computer can be either a server or a client. The program shares four classes: A listener class (used to listen to new connections), a sender class (used to send information), and an inputhandler class (used to control input), an initialize class (used to complete initialization ). Next, I will introduce these four classes first, and finally give the specific implementation method of the program.

II. Introduction to basic classes:

1. Listener class:

The listener class is used to listen for new connections. When an object is created and enabled, the object starts to listen continuously for connection requests from the network. Once a connection request is sent, the object tries to establish a connection and obtain its byte stream, which is then converted into a string and displayed on the console. When a connection ends, the object continues to listen for connection requests from the network.

CodeAnd the notes are as follows:

Namespace p2ptest
{
Using system;
Using system. net. Sockets;
Using system. Threading;

Public class listener
{
Private thread th;
Private tcplistener tcpl;
Public bool listenerrun = true;
// If listenerrun is set to true, the connection request is accepted. If false, the end program is used.

Public listener () // Constructor
{
Th = new thread (New threadstart (Listen); // create a thread for listening
Th. Start (); // open a new thread
}

Public void stop ()
{
Tcpl. Stop ();
Th. Abort (); // terminate the thread
}

Private void listen ()
{
Try
{
Tcpl = new tcplistener (5656); // create a tcplistener object on port 5656
Tcpl. Start ();
Console. writeline ("started listening ..");

While (listenerrun) // start listening
{
Socket S = tcpl. acceptsocket ();
String remote = S. remoteendpoint. tostring ();
Byte [] stream = new byte [80];
Int I = S. Receive (Stream); // The byte stream that receives the connection request
String MSG = "<" + Remote + ">" + system. Text. encoding. utf8.getstring (Stream );
Console. writeline (MSG); // display strings on the console
}
}
Catch (system. Security. securityexception)
{
Console. writeline ("firewall says no to application-application cries ..");
}
Catch (exception)
{
Console. writeline ("stoped listening ..");
}
}
}
}

Description of the listen () function:

This function is the core part of the listener class. This function is called by the constructor first. If the Boolean value listenerrun is true, we can create and start a TCP listening object tcplistener on port 5656 to listen for connection requests in the network. Once listenerrun is set to false, it indicates that the program is finished. Inside the loop body, we first accept a connection and use S. remoteendpoint to obtain its IP address and Its byte stream. Based on the obtained byte stream, we use utf8 encoding to convert it into a string. Finally, we will display the obtained string in the console.

For catch statements, the first block captures an exception that may be caused by the firewall. For the firewall, it may think it is a Troy trojan or a Confucian virus, so it will refuse to pass. The solution is to reconfigure the firewall. The second block is used to capture General exceptions. For example, when we call the stop () function and destroy the tcplistener object, it is naturally impossible to listen again.

2. Sender class:

The sender class is a function, so it is quite simple.

The code and comments are as follows:

Namespace p2ptest
{
Using system;
Using system. IO;
Using system. net. Sockets;

Public class sender
{
Public void send (string [] ainput)
{
String stream = "";
// Obtain the information to be sent
For (INT I = 2; I <ainput. length; I ++)
{
Stream + = ainput [I] + "";
}

Try
{
Tcpclient TCPC = new tcpclient (ainput [1], 5656 );
// Create a tcpclient object on port 5656
Networkstream tcpstream = TCPC. getstream ();

Streamwriter reqstreamw = new streamwriter (tcpstream );
Reqstreamw. Write (Stream );
Reqstreamw. Flush (); // send information
Tcpstream. Close ();
TCPC. Close ();
}
Catch (exception)
{
Console. writeline ("connection refused by target computer ");
}
}
}
}

Description of the send () function:

The send (string [] ainput) function uses an array as a parameter. The first element of the array, send (ainput [0]), must contain the word "send"; otherwise, the sender object will not be created (more content is in the inputhandler class ); the second element contains the IP address of the target computer, and the rest is the content to be sent.

In the try block, a tcpclient object is created on port 5656 Based on the IP address of the remote computer. Then, we create a networkstream and a stremwriter object to send our information. In the Catch Block, we use it to capture general exceptions, such as remote computers rejecting connection requests or network failures.

3. inputhandler class:

The inputhandler class is mainly used to control user input.

The code and comments are as follows:

Namespace p2ptest
{
Using system;

Public class inputhandler
{
Public bool apprun = true; // when apprun is false, the program ends.
Public inputhandler ()
{
Console. writeline ("type help for a list of commands .");
Input ();
}

Private Static listener Li; // a static listener object
Private string inparam;
Private string [] ainput; // array ainput is used to accept user input information

Public void input ()
{
While (apprun)
{
Inparam = console. Readline ();
Ainput = inparam. Split ('');
// The purpose of inparam splitting is to obtain the first word in the string and execute the following different commands:
Switch (ainput [0])
{
Case "send": // if it is "send", a new sender object is created and the message is sent.
Sender Se = new sender ();
Se. Send (ainput );
Break;
Case "start": // if it is "start", the new start listener
Try
{
Li. listenerrun = false;
Li. Stop ();
}
Catch (nullreferenceexception)
{
;
}
Finally
{
Li = new listener ();
}
Break;
Case "stop": // if it is "stop", stop listening
Try
{
Li. listenerrun = false;
Li. Stop ();
}
Catch (nullreferenceexception)
{
;
}
Break;
Case "exit": // exit the program
Try
{
Li. listenerrun = false;
Li. Stop ();
}
Catch (nullreferenceexception)
{
;
}
Finally
{
Apprun = false;
}
Break;
Case "help": // display help information
Console. writeline ("commands :");
Console. writeline ("START: starts the listener ");
Console. writeline ("Stop: stops the listener if started ");
Console. writeline ("Send: Send <ip> <message> sends a message ");
Console. writeline ("Exit: exits the application ");
Console. writeline ("Help: You already know ");
Break;
Default:
Console. writeline ("invalid command ");
Break;
}
}
}
}
}

Description of the inputhandler class:

This class has a static listener object Li. Once the computer runs this program and runs the "Start" operation, the computer can become a server on the network to listen to connection requests from other computers. The core part of this class is a switch case statement series. Different operations allow the computer to assume different roles: the "send" operation indicates that the computer is a client relative to the target computer; the "start" operation sets the computer itself as the server, which reflects the principle of "non-Centralization" of P2P, both the server and the client; at the same time, the program also provides some other auxiliary operations.

4. initialize class:

The initialize class initializes the program. It creates an inputhandler object and runs it until the value is false and the program exits.

The code and comments are as follows:

Namespace p2ptest
{
Using system;

Public class init
{
Public static void main ()
{
Inputhandler ih = new inputhandler (); // create an inputhandler object
While (ih. apprun); // until ih. apprun is false, the program exits
Console. writeline ("exiting ..");
}
}
}

So far, the four classes have been introduced, and I think you can't wait for them. The following is a brief introduction to the specific implementation methods of the program.

Iii. Implementation Method:

First, open Visual Studio. NET and create a Visual C # project named p2ptest console application, as shown below:


Figure 1

The preceding four classes are saved as four files: listener. CS, Sender. CS, inputhandler. CS, and initialize. CS. Then add the four files to the current project and delete the original master file (because the main function already exists in Initialize. CS ).

Finally, press Ctrl + F5 to execute the program.

To perform the test, we need to open two p2ptest programs, one as the server and the other as the client. The following figure shows the server (the listener is started now ):


Figure 2

The following figure shows the client. (enter the command line: Send 10.85.7.79 hello, I'm Pitt. Can you hear me ??) :


Figure 3

Let's look at the server's situation, as shown in the figure below:


Figure 4

The following figure shows that the server has received the message. At the same time, as long as the client has enabled the listening function, the server can send messages to the client. In this way, their relationship is no longer the server-client relationship, but the peer-to-peer relationship.

Iv. Summary:

Now we have a basic P2P application and complete it. Through it, we can use the basic features of P2P technology to achieve point-to-point communication. Through this program, I believe that everyone should have a general understanding of P2P programming under C. The disadvantage of this program is that the function is relatively simple. It can only send and accept information, and it is still based on the console, readers can try to develop more powerful Windows Forms-Based P2P applications.

Finally, I hope to use this article to arouse everyone's interest in P2P technology. The incomparable creativity behind P2P makes people have a good vision for the future of the Internet. The P2P application boom in the world is also a wave of waves. In the foreseeable future, with the further development of P2P research and the increasing number of P2P groups, P2P will inevitably enter a new era of rapid development.

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.