C # Manage Socket implementation method (2)

zhaozj2021-02-16  82

three. This article describes the design, debugging, and running software environment:

(1). Microsoft Window 2000 Server Edition

(2) .visual studio .NET official version, .NET Framework SDK version number 3705

four. Use Socket to send data:

Visual C # should pay attention to the solution to the following questions when using Socket to transfer data:

1. Create a Socket instance, use this instance to create and remote endpoints, and determine if the connection is successfully established.

2. Send data to the socket to implement data transfer.

These problem solutions can find the corresponding part of the code in the code below. Due to detailed annotations due to the following code,

It will not be described in detail here. Below is a specific implementation step using Socket transfer data:

1. Start Visual Studio .NET, and create a new Visual C # item,

The project name is [uses socket to send data].

2. Detach the current window of Visual Studio .Nejei, Orm1.cs (Design)] window,

And drag into the following components from the [Windows Forms] tab in [Windows Forms] tab in [Toolbox] and perform the appropriate operations:

Two TextBox components, an IP address for entering the remote host, one to enter data transmitted toward the remote host.

A Stausbar component is used to display the health of the program.

A ListBox component is used to display data information transmitted by the program.

Three Label components.

Two Button components, named button1, button2, respectively, and after the two components are dragged into the form, double-click them separately, the system automatically generates the Click event corresponding to the two components in the Form1.cs file. Code.

3. In the [Solution Explorer] window, double-click the Form1.cs file to enter the editing interface of the Form1.cs file.

4. The following code alternatives the INITIALIZECMPONENT process generated by the system:

Private vidinitiRizeComponent ()

{

THIS.LABEL1 = New System.windows.Forms.label ();

This.TextBox1 = new system.windows.Forms.TextBox ();

This.button1 = new system.windows.Forms.Button ();

THIS.LABEL2 = New System.windows.Forms.label ();

This.TextBox2 = new system.windows.Forms.TextBox ();

This.listbox1 = new system.windows.forms.listbox ();

This.statusbar1 = new system.windows.Forms.statusbar ();

This.label3 = new system.windows.Forms.label ();

This.Button2 = new system.windows.Forms.Button ();

THIS.SUSPENDLAYOUT ();

THIS.Label1.Location = new system.drawing.point (24, 20);

THIS.LABEL1.NAME = "label1";

This.Label1.size = new system.drawing.size (74, 30); this.label1.tabindex = 0;

This.Label1.Text = "IP address:";

This.TextBox1.Borderstyle = System.Windows.

Forms.Borderstyle.fixedsingle;

This.TextBox1.Location = new system.drawing.point (94, 18);

THIS.TEXTBOX1.NAME = "TextBox1";

THIS.TEXTBOX1.SIZE = New System.drawing.size (166, 21);

this.TextBox1.tabindex = 1;

THIS.TEXTBOX1.TEXT = "";

This.button1.flatstyle = system.windows.Forms.Flatstyle.FLAT;

This.Button1.Location = new system.drawing.point (280, 14);

This.button1.name = "button1";

This.button1.size = new system.drawing.size (62, 28);

this.button1.tabindex = 2;

This.Button1.Text = "Connect";

This.Button1.click = new system.eventhandler (this.button1_click);

THIS.LABEL2.LOCATION = New System.drawing.Point (16, 64);

THIS.LABEL2.NAME = "label2";

THIS.Label2.tabindex = 3;

THIS.Label2.Text = "Send information:";

This.TextBox2.Borderstyle = System.Windows.

Forms.Borderstyle.fixedsingle;

This.TextBox2.Location = New System.drawing.Point (94, 58);

THIS.TEXTBOX2.NAME = "TextBox2";

THIS.TEXTBOX2.SIZE = New System.drawing.size (166, 21);

this.TextBox2.tabindex = 4;

THIS.TEXTBOX2.TEXT = "";

THISTBOX1.ItemHeight = 12;

this.listbox1.location = new system.drawing.point (20, 118);

this.listbox1.name = "listbox1";

This.listbox1.size = new system.drawing.size (336, 160);

THISTBOX1.TABINDEX = 6;

THIS.STATUSBAR1.LOCATION = New System.drawing.Point (0, 295);

THIS.STATUSBAR1.NAME = "statusbar1"; this.statusbar1.size = new system.drawing.size (370, 22);

THIS.STATUSBAR1.TABINDEX = 7;

This.statusbar1.text = "No connection";

THIS.Label3.Location = new system.drawing.point (14, 94);

THIS.LABEL3.NAME = "label3";

THIS.Label3.Size = new system.drawing.size (128, 23);

THIS.Label3.tabindex = 8;

This.Label3.Text = "The information already sent:";

This.button2.flatstyle = system.windows.Forms.Flatstyle.FLAT;

This.Button2.Location = new system.drawing.point (280, 54);

This.Button2.name = "button2";

This.button2.size = new system.drawing.size (62, 28);

this.button2.tabindex = 9;

This.button2.text = "Send";

this.button2.click = new system.eventhandler

(this.button2_click);

THIS.AUTOSCALEBASESIZE = New System.drawing.size (6, 14);

This.ClientSize = New System.drawing.size (370, 317);

this.controls.addrange (new system.windows.forms.control] {

this.button2,

this.statusbar1,

THISTBOX1,

THIS.TEXTBOX2,

THIS.LABEL2,

this.button1,

this.TextBox1,

THIS.LABEL1,

THIS.LABEL3});

This.FormBorderstyle = system.

Windows.Forms.FormBorderstyle.fixedsingle;

THIS.MAXIMIZEBOX = FALSE;

THIS.NAME = "Form1";

This.Text = "Use Socket to send data";

This.ResumeLayout (false);

}

To this [use sokcet to send data] The interface after the project is completed.

5. Advocated the code area of ​​the named space in the beginning of the Form1.cs file, add the following code,

The following code is the namespace where the class used in the following program is imported:

Using system;

Using system.drawing;

Using system.collections;

Using system.componentmodel;

Using system.windows.forms;

Using system.data;

Using system.net.sockets;

// Use the TCPListen class

Using system.net;

6. Add the following code to the CLASS code area of ​​Form1, the following code is to define the instance of global variables and creation global use:

INT port = 8000;

/ / Define the listening port number

PRIVATE TCPCPCLIENT TCPC;

/ / Create a TCP connection to the server side

Private socket stsend;

// Create a sending data socket

PRIVATE BOOL TCPCONNECT = FALSE;

// Define the identifier to indicate whether the TCP connection is established.

7. Replace the processing code corresponding to the Click event of the Button1 component in Form1.cs with the following code, the function of the following code is initialized to create the Socket instance, and make an application to the remote endpoint, and determine if the connection is established:

Private void button1_click

(Object Sender, System.EventArgs E)

{

// The following code is judging whether or not the remote endpoint is successful

Try

{

StSend = New Socket (AddressFamily.InterneTWork,

Sockettype.stream, protocoltype.tcp;

// Initialize a Socket instance

IpendPoint Tempremoteip = new iPENDPOINT

(Ipaddress.parse (TextBox1.text), Port);

/ / Create a remote endpoint according to IP address and port number

Endpoint eptemp = (endpoint) TempRemoteIP;

StSEND.CONNECT (EPTEMP);

/ / Connect the 8000 port number of the remote host

STATUSBAR1.TEXT = "successfully connected remote computer!";

TcpConnect = true;

Button1.enabled = false;

Button2.enabled = True;

}

Catch (Exception)

{

STATUSBAR1.TEXT = "Target computer refuses to connect the request!";

}

}

8. Replace the processing code corresponding to the Click event of the Button2 component in Form1.cs with the following code, the function of the following code is to transmit data to the remote host by using the Socket with the Socket.

Private void button2_click

(Object Sender, System.EventArgs E)

{

INT ILENGTH = TEXTBOX2.TEXT.LENGTH;

/ / Get the length of the data to be sent

Byte [] bysend = new byte [inength];

/ / Define a Byte type array according to the length of the acquisition

BYSEND = system.text.Encoding.default.getbytes

(TextBox2.text);

/ / Specify the string to the specified Byte array according to the specified encoding type

INT i = stsend.send (bysend);

//send data

ListBox1.items.add (TextBox2.text);

}

9. Replace Form1.cs with the following code "Clean all the resources being used." The corresponding code. Its role is to determine the connection state before the program exits. If not exit, the remote host sends the control code "STOP" to disconnect and remotely connect, and clear the corresponding resources. The so-called control code is a custom codon that exchanges information between network applications. The application uses it to transmit these codes, which can clarify the behavior of the network application, guarantee the consistency of the execution, and there is a lot of error chances. . The control code is more used in writing remote control applications. This step is because many people have encountered such a situation when writing network applications with Visual C #. 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. It can be seen that in some cases, the garbage collector relying on Visual C # cannot guarantee full recycling resources, and we need to manually recycle resources. Below is a way to manually recycle resources: protected override void dispose (Bool Disposing)

{

IF (TCPConnect)

{

Byte [] bysend = new byte [4];

/ / Define byte array based on the length of the string "STOP"

BYSEND = system.text.Encoding.

DEFAULT.GETBYTES ("STOP");

INT i = stsend.send (bysend);

// Send a control code

StSend.Close ();

// Close the socket

}

IF (Disposing)

{

IF (Components! = NULL)

{

Components.dispose ();

}

}

Base.dispose (Disposing);

}

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

New Post(0)