Use Visual C # to implement local area network point communication
Author: Ma Jinhu Date: 2003-9-28 Source: P2P China (PPcn.net)
Point-to-point, Peer-to-Peer, is usually short-handed as P2P. The so-called point-to-point in the network can actually be seen as a network model for equalization. P2P is actually a technology between different computers on the network, without trunk devices directly exchange data or services. P2P Since any computer allows a computer to be directly connected to other computers in the network, data exchange is exchanged, which eliminates the intermediate link, which makes communication on the network easier, more direct. The P2P is a model of a network that is different from the traditional client / server model. Customer / server models typically have predefined clients and servers. In the P2P model, there is no clear client and server, but in actually in the P2P model, each computer can be regarded as a server, or it can be regarded as a client. In the network, in the traditional client / server communication model, the service request or the transmitted computer is transmitted, generally referred to as a client; and the computer receiving, processing, or receiving data is referred to as a server. In the P2P network model, the computer not only receives data, but also transmits data, not only the service request, but also receives the other party's service request. In the following, a local area network-to-point communication program implemented by Visual C #, there is a following characteristics, any computer that uses this communication program to communicate, before the communication, you need to listen to the port number, accept the connection application of other machines. And after the connection is established, the data sent by the other party can be received; and the connection application can be proposed to other machines, and the data to each other will be transmitted after the other machine allows the connection request to be established. It can be seen that any computer that uses this software in the network for P2P network communication is both a client, and it is also a server. One. Program design, debug, running software environment: (1). Microsoft Window 2000 Server Edition (2) .visual Studio .NET official version, .NET Framework SDK version number 3705 II. Key Steps and Solution: Key Steps are the transmission and reception of information in the network. The data received is a socket, and the data is sent is NETWORKSTREAM. 1. Using Socket to receive information: For more clear explanation, the program uses a non-passing port number when processing data transmission and reception, and transmits the port number set by the default state in the default state "8889.
The following code is the listening port number "8889", accepts the connection request for this port number in the network, and after establishing the connection, receive the data sent by the remote computer via Socket: try {tcplistener tllisten1 = new TCPListener (8889); / / Listening port number Tllisten1.Start (); socket SKSocket = tllisten1.acceptsocket (); // Accept remote computer connection request and get a socket instance endpoint tempRemoteEp = SKSOCKET.RemoteEndPoint; // get a remote computer for receiving data Corresponding network remote endpoint while (true) {byte [] bystream = new byte [80]; // Define data buffer INT i = SKSocket.ReceiveFrom (BYSTREAM, REF TEMPREMOTEEP); / / / Receive data, and store String SMESSAGE = system.text.Encoding.utf8.getstring (bystream); // by the specified encoding, from the buffer, the content MessageBox.show (SMESSAGE); / / Display data}} catch (system.security.securityException) {MessageBox.show ("Firewall Security Error!", "Error", MessageBoxButtons.ok, MessageBoxicon.exclamation;} 2. Take the networkStream to transfer information: When using the streamwriter to process the data transmission data, the encoding type of the data transfer is "UTF8", the following code is the "8888" port number of the IP address is "10.138.198.213", and the application is applied, and after the connection is established, Sending a string in UTF8, "Hello, see you is very happy" to each other, because the comments in the following code are more detailed, this is not specifically introduced, the following code is also using NetWorkst REAM transmitted data: try {tcpclient tcpc = new TcpClient ("10.138.198.213", 8888); // Subproducing connection application networkStream tcpstream = tcpc.getStream ); // If the connection request is established, a data stream for transmitting data is obtained} catch ("target computer refuses to join the request! "); Break;} try {string smsg =" Hello, see you is very happy "; streamWriter ReqStreamw = new streamwriter (TCPSTream); // Write data in a specific code to the data stream, default is UTF8 encoding ReqStreamw.write (SMSG); // writes the string in the data stream ReqStreamW.flush ();
/ / Clean all the buffers of the current writer and write all buffer data to the base stream} catch ("unable to send messages to the target computer!");} Of course, in specific Visual C # implementation When the network point is pairpoints the program, you must also master a lot of other knowledge, such as resource recovery. When writing a network application with Visual C #, many friends encounter such a situation. When the program exits, the "Explorer" "Explorer" through Windows is that the number of processes is not reduced. This is because the threads used in the program may not be effectively exit. Although the "Abort" method is provided in the Thread class to abort the process, it is not guaranteed to successfully exit. Since some resources used in the process are not recycled. In some cases the garbage collector does not guarantee full recycling resources, or we need to manually recycle resources. The procedures in this article also involve resource manual recovery. Implementation methods can refer to the twelfth step in the specific implementation steps below. three. Specific steps: After understanding, after mastering the key problems above and its solution, re-implementing the Visual C # to realize the network point to the point communication program is much easier, the following is a specific implementation step: 1. Start Visual Studio .NET, and Newly built a Visual C # project, named [Visual C # implement network point-to-point communication program]. 2. In the [Solution Explorer] window in the Visual Studio .NET integration development environment, double-click the Form1.cs file to enter the editing interface of the Form1.cs file. 3. In the beginning of the Form1.cs file, import the namespace code replacement system default import namespace code with the following. using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net.Sockets; using System.Net; using System.IO; using System. Using system.threading; 4. Turn the current window of Visual Studio.net to the [Windows Forms] tab in the [Windows Forms] tab in [Windows Forms] tab from [Toolbox] Drop the following components: four Button components; two listbox components; four TextBox components; a StatusBar component; five Label components. After the four Button components are dragged into the form, double-click them separately in the Form Design interface, and the system will generate the processing code corresponding to the four components in the Form1.cs file. 5. In the [Solution Explorer] window, double-click the Form1.cs file to enter the editing interface of the Form1.cs file. The following code is the INITIALIZECMPONENT process generated by the system.
The following code is initialized for the components added above: private void initializecomponent () {this.listbox1 = new system.windows.forms.listbox (); this.textbox1 = new system.windows.Forms.TextBox (); this.label3 = new system.windows.forms.label (); this.label2 = new system.windows.forms.label (); this.textbox3 = new system.windows.forms.textbox (); this.button1 = new System.Windows .Form.Button (); this.textbox2 = new system.windows.forms.textbox (); this.label1 = new system.windows.forms.label (); this.label4 = new system.windows.forms.label This.label5 = new system.windows.forms.label (); this.button2 = new system.windows.Forms.Button () (); this.button3 = new system.windows.Forms.Button (); this.button4 = new System.Windows.Forms.Button (); this.textBox4 = new System.Windows.Forms.TextBox (); this.statusBar1 = new System.Windows.Forms.StatusBar (); this.statusBarPanel1 = new System.Windows .Forms.statusbarpanel (); this.statusbarpanel2 = new system.windo ws.Forms.StatusBarPanel (); this.label6 = new System.Windows.Forms.Label (); this.listBox2 = new System.Windows.Forms.ListBox (); ((System.ComponentModel.ISupportInitialize) (this.statusBarPanel1 )) .BeginInit (); ((System.ComponentModel.ISupportInitialize) (this.statusBarPanel2)) .BeginInit (); this.SuspendLayout (); this.listBox1.ItemHeight = 12; this.listBox1.Location = new System.Drawing .Point (122, 110); this.listbox1.name = "listbox1"; this.listbox1.size = new system.drawing.size (212, 88); this.listbox1.tabindex = 4; this.textbox1.location =
New system.drawing.point (122, 18); this.textbox1.name = "textbox1"; this.textBox1.size = new system.drawing.size (210, 21); this.TextBox1.tabindex = 1; this. TextBox1.text = ""; this.label3.Location = new system.drawing.point (220, 52); this.label3.name = "label3"; this.label3.size = new system.drawing.size (66, 23); this.Label3.Tabindex = 7; this.label3.text = "local port:"; this.label2.location = new system.drawing.point (38, 54); this.Label2.name = "label2" This.label2.size = new system.drawing.size (80, 23); this.label2.tabindex = 20; this.label2.text = "remote port number:"; this.TextBox3.Location = new system.drawing .Point (294, 50); this.textbox3.name = "textbox3"; this.textbox3.size = new system.drawing.size (38, 21); this.textBox3.TabINDEX = 3; this.TextBox3.text = "8889"; this.button1.flatstyle = system.windows.forms.flatstyle.flat; this.button1.location = new system.drawing.point (348, 16); this.button1 .Name = "button1"; this.button1.size = new system.drawing.size (92, 40); this.button1.tabindex = 6; this.button1.text = "Connect remote machine"; this.button1.click = new System.EventHandler (this.button1_Click); this.textBox2.Location = new System.Drawing.Point (122, 50); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing .Size (38, 21); this.TextBox2.Tabindex = 2; this.textBox2.text = "8888"; this.label1.Location = new system.drawing.point (38, 22);
THIS.Label1.Name = "label1"; this.label1.size = new system.drawing.size (80, 23); this.label1.tabindex = 16; this.label1.text = "remote IP address:"; THIS .label4.location = new system.drawing.point (50, 84); this.label4.name = "label4"; this.label4.size = new system.drawing.size (66, 23); this.label4.tabindex = 23; this.label4.text = "Send information:"; this.label5.Location = new system.drawing.point (36, 112); this.label5.name = "label5"; this.label5.size = new System.drawing.size (80, 23); this.label5.tabindex = 24; this.Label5.Text = "Information:"; this.button2.enabled = false; this.button2.flatstyle = system.windows. Forms.flatstyle.Flat; this.button2.location = new system.drawing.point (352, 192); this.button2.name = "button2"; this.button2.size = new system.drawing.size (92, 40 This.button2.tabindex = 7; this.button2.text = "Disconnect"; this.button2.click = new system.eventhandler (this.button2_click; this.button3.flatstyle = System.Windows.Forms.Flatstyle.Flat; this.button3.location = new system.drawing.point (348, 74); this.button3.name = "button3"; this.button3.size = new system.drawing. Size (92, 40); this.button3.tabindex = 8; this.button3.text = "Listening port"; this.button3.click = new system.eventhandler (this.button3_click); this.button4.enabled = False; this.button4.flatstyle = system.windows.Forms.Flatstyle.FLAT; this.button4.location = new system.drawing.point (350, 132);
This.button4.name = "button4"; this.button4.size = new system.drawing.size (92, 40); this.button4.tabindex = 9; this.button4.text = "send information"; this.button4 .Click = new System.EventHandler (this.button4_Click); this.textBox4.Location = new System.Drawing.Point (122, 82); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System .Drawing.size (212, 21); this.TextBox4.Tabindex = 25; this.textBox4.text = ""; this.statusbar1.location = new system.drawing.point (0, 301); this.statusbar1.name = "statusBar1"; this.statusBar1.Panels.AddRange (new System.Windows.Forms StatusBarPanel [] {this.statusBarPanel1, this.statusBarPanel2}.); this.statusBar1.ShowPanels = true; this.statusBar1.Size = new System .Drawing.size (456, 22); this.statusbar1.tabindex = 26; this.statusbarpanel1.width = 200; this.statusbarpanel2.width = 230; this.label6.Location = new system.drawing.point (48, 210 This.label6.name = "label6"; This.Label6.Size = new system.drawing.size (66, 23); this.Label6.Tabindex = 28; this.Label6.text = "Receive information:"; this.listbox2.itemHeight = 12; this.listbox2. Location = new system.drawing.point (122, 206); this.listbox2.name = "listbox2"; this.listbox2.size = new system.drawing.size (214, 88); this.listbox2.tabindex = 27; this. AutoScaleBasesize = new system.drawing.size (6, 14); this.clientsize = new system.drawing.size (456, 323);
This.Controls.addrange (new system.windows.forms.control [] {this.label6, this.listbox2, this.statusbar1, this.textbox4, this.button4, this.button3, this.button2, this.label5, this .label4, this.label2, this.textBox3, this.button1, this.textBox2, this.label1, this.label3, this.textBox1, this.listBox1}); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle FixedSingle. this.maximizebox = false; this.name = "form1"; this.text = "Visual C # Implement Network Point-to-point communication program"; this.Load = new system.EventHandler (this.form1_load); ((System.comPonentModel); .Isupportinitialize (this.statusbarpanel1))) .ndinit (); (this.statusbarpanel2) .ndinit (); this.ResumeLayout (false);} to this point, [Visual C # Implement network point-to-point Communication program] The previous work of the interface interface design and functionality is completed, the design interface is shown in Figure 1: Figure 1 Design interface of the item 6. In the [Solution Explorer] window, double-click Form1.cs file, Go to the editing interface of the Form1.cs file. And in the definition of the FORM class member code area, the following code is added, the following code is the role of the following code to define global variables used in the program.
Private thread th; // Create a thread to listen to the port number, receive information private tcplistener tllisten1; // to listen to the port number private bool listenerrun = true; // Set the lase bit, determine the listening state Private NetworkStream TcpStream ; // Create a transfer / received basic data stream instance private streamWriter ReqStreamw; // to implement transmit information private tcpclient tcpc to remote hosts; // to create connection private socket sksocket for remote hosts; // to receive remote The data transmitted by the host 7. Replace the code corresponding to the "Click" event of the "Click" event of the Button1 component in Form1.cs with the following code, the following code is to make a connection application to the remote computer. If the connection is established, the data source of transmitting data is obtained. : private void button1_Click (object sender, System.EventArgs e) {try {tcpc = new TcpClient (textBox1.Text, Int32.Parse (textBox3.Text)); // the connection request made to the remote computer tcpStream = tcpc.GetStream () // If the connection request is established, it is obtained to transmit data statusbar1.panels [0] .text = "successfully connected remote computer!"; Button2.enabled = true; button1.enabled = false; button4.enabled = True;} cats (exception) {statusbar1.panels [0] .text = "Target computer reject connection request!";}} 8. After the main function in Form1.cs, add the following code, the following code is defined a name Process for "Listen": private void listen () {try {tllisten1 = new TCPListener (int32.parse (textBox2.text)); tllisten1.start (); // Listening Specify port number statusbar1.panels [1] .text = "Listening ..."; // Accept the connection request of the remote computer, and get the socket instance SKSocket = Tllisten1.acceptsocket () to receive data (// get a remote computer network remote endpoint corresponding endPoint tempRemoteEP = skSocket.RemoteEndPoint; IPEndPoint tempRemoteIP = (IPEndPoint) tempRemoteEP; IPHostEntry host = Dns.GetHostByAddress (tempRemoteIP.Address); string HostName = host.HostName; // the remote computer corresponding to the obtained Network remote endpoint gets the name of the remote computer statusbar1.panels [1] .text = " " "" "remote computer correctly! "
// Loop listening while (listenerrun) {byte [] stream = new byte [80]; // Defines the data buffer String Time = DATETIME.NOW.TOSTRING () to receive data storage from the remote computer to receive data; // Get the current Time INT i = SKSocket.ReceiveFrom (Stream, Ref TempRemoteep); // Received data, and stores String SMESSAGE = System.Text.Encoding.utf8. GetString (stream); // at the specified encoding (station); // From the buffer in the buffer ListBox2.Items.Add (Time " Hostname ": "); listbox2.items.add (smessage); // Display received data}} catch (system.security.securityException) {MessageBox.show ("Firewall Security Error!", "Error", MessageBoxButtons.ok, MessageBoxicon.Exclamation;}} 9. Replace the Click event of the Button2 component in Form1.cs with the following code, the following code The role is to disconnect the current connection: private void button2_click (object sender, system.eventargs e) {listenerrun = false; tcpc.close (); statusbar1.panels [0] .text = "Disconnect!"; Button1. Enabled = true; button2.enabled = false; button 10. Replacing the Click event corresponding to the Click event of the Button3 component in Form1.cs with the following code, the following code is the Listen process defined above. Initialize thread example, start thread, achieve the purpose of listening port: private void button3_click (Object Sender, System.Eventargs E) {THREADSTART (New ThreadStart (Listen)); // Initialize thread instance th.Start (); // starts this thread with the listen process} 11. Replace FORM1.CS with the following code. The Click event of the button4 component corresponds to the processing code. The following code is to send information to the specified port number of the remote computer.
Private void button4_click (object sender, system.eventargs e) {Try {string smsg = textBox4.text; string myname = dns.getHostName (); // Write data in a specific code to the data stream, // default UTF8Encoding instance ReqStreamW = new streamWriter (TCPSTREAM); // writes a string to the data stream (SMSG); / / Clean all buffers of the current writer and write all buffer data to the base stream ReqStreamw. Flush (); string time = datetime.now.tostring (); // Displays the transferred data and time Listbox1.Items.Add (Time " MyName ": "); listbox1.items.add (smsg); TextBox4.clear ();} // Exception {statusbar1.panels [0] .text = "Unable to send information to target computer!";}} 12. Replace "Dispose" in Form1.cs with the following code "The process corresponding to the process, the following code is to clear the resource without recycling after the program is exited: protected override void dispose; th.abort (); TH = null; tllisten1. STOP (); SKSocket.close (); tcpc.close ();} catCh {} f (disponents! = Null) {components.dispose ();}}}}}}}}}} Base.Dispose Run the program, implement the network point to point communication: Click the shortcut key F5 compile successfully, distribute this program into the two computers in the network. Enter the listening port number correctly, the remote computer IP address, the remote port number is correct, click the [Listening Port] and the [Connect the Remote Machine] button to establish a chat. The chat is chatted by the [Send Information] button. Figure 2 is an operation interface when communicating. Figure 2 Run the interface. Summary: Network Point-to-point communication program is not like client / server model programs, allocated into client programs and server-side programs. It is a client program and server-side program and one, so it is relatively troublesome in specific programming. Examples described above in Visual C # to realize network point communication point communication, although the structure is not complicated, the knowledge involved is relatively wide. As in the example, many of many network functions are involved, such as listening port numbers, establishing connections, transmitting data, and receiving data, etc., also involves processing, resource recovery, etc. It is understood that it is necessary to process the processing of these issues to prepare more complex web applications.