Visual C # hosts Socket implementation method (reproduced people's articles, take a collection!)

xiaoxiao2021-03-06  45

Managed Visual C # Socket implementation method (a) (1) Author: Wang Tian dispatch time: 2003.11.19 Socket socket is, it is network programming concepts and tools most commonly encountered. In the TCP / IP network, transmit and receive data often use to Socket, because complex data can be processed on the network using Socket, which involves data transfer and reception, usually use Socket, It can be seen that you have to master the network programming, which is very important to master Socket. Due to the complexity of the socket itself, it is more difficult to master it. Visual C # is the main language recommended by Microsoft's recommendation. With .NET's deep people, there are currently many far-sighted companies to turn the previous software to the .NET platform. Mastering Network Programming is always the focus of learning a development language. This is the same for Visual C #. Visual C # Implementing Network Functions Its key is also the method of use of managed Socket. This article describes the implementation methods of using managed Socket to realize network data transfer and reception in Visual C # and their precautions.

One. Visual C # Operation Socket:

Although Visual C # can be transmitted, receive data, but NetWorkStream is very limited in use, using NetWorkStream only transmits and receives data type data, and if you want to transfer some complex data such as: binary data Wait, it seems to be limited. However, when using NetWorkStream to handle itself, it is more convenient than Socket. Socket can almost handle any data types that need to be transmitted in the network.

We know that the difference between Visual C # and Visual C is that Visual C # does not belong to your own class library, and Visual C is there, Visual C # The class library used by Visual C # is the .NET framework for all development .NET platform programs A common class library provided by the language - .NET Framework SDK. Visual C # primary network features primarily use the two namespaces "System.Net.Sockets" and "System.Net" in the .NET Framework SDK. The implementation of the socket is the Socket class in the namespace "System.Net.sockTs". Visual C # Implements the host of the Socket by creating an instance of the Socket class. After you create a socket instance in Visual C #, you can bind to the endpoints specified in the network through this Socket instance, or you can establish a connection to the specified endpoint through its Connect method. After the connection is created, you can send the data to the socket using its Send or Sendto method; you can read data from the socket using its Receive or ReceiveFrom method. After the Socket is used, use its Shutdown method to disable the socket and use the Close method to close the socket. Tables 01 and Table 02 are common attributes and methods in the socket class and their brief description.

Property description

AddressFamily Gets the address family of Socket.

Available Gets the amount of data that has been received from the network and is available.

Blocking gets or sets a value indicating whether the socket is in blocking mode.

Connected gets a value that indicates whether the socket is connected to the remote resource.

Handle Gets the operating system handle of the socket. LocalendPoint Gets the local endpoint.

ProtocolType Gets the protocol type of the socket.

RemoteEndPoint Gets the remote endpoint.

SocketType Gets the type of socket.

Table 01: Common properties and descriptions of the Socket class

Method description

Accept creates a new Socket to process incoming connection requests.

BeginAccept starts an asynchronous request to create a new Socket to accept incoming connection requests.

BeGinconnect starts an asynchronous request to connect to the network device.

BeginReceive starts receiving data from the connected socket.

BeginReceiveFrom starts receiving data from the specified network device.

Beginsend sends data asynchronously to the connection

BeGinsendto sends data to a particular remote host.

Bind causes the socket associated with a local endpoint.

Close enforces socket connection to close.

Connect is established to the remote device.

Endaccept ends asynchronous requests to create new sockets to receive incoming connection requests

EndConnect ends the pending asynchronous connection request.

EndRecEive ends the pending asynchronous reading.

EndReceiveFrom ends hang, asynchronously read from a specific endpoint.

Endsend ends the pending asynchronous transmission

EndsendTo ends the pending and sends asynchronous to the specified location.

GetSocketOption returns the value of the socket option.

IOCONTROL Sets low-level operating modes for Socket

Listen places Socket in a listening state.

Poll

Receive receives data from the connection socket.

ReceiveFrom receives the data text report and stores the source endpoint.

SELECT determines the status of one or more sockets.

Send sends the data to the connection

Sendto sends data to a specific endpoint.

SetSocketOption Sets the socket option.

Shutdown disables sending and receiving on a Socket.

Table 02: Common methods of Socket class and its description

Among them, "Beginaccept" and "Endaccept", "BeginConnect" and "EndConnect",

"BeginReceive" and "Endreceive", "BeginReceiveFrom", and "EndreceiveFrom",

"Beginsend" and "endsend", "beginsendto" and "endsendto" are six sets of asynchronous methods,

Its functionality is equivalent to "Accept", "Connect", "Receive", "ReceiveFrom",

"Send" and "Sendto" methods.

Below, the specific method is introduced to how to implement data transfer and reception through managed Socket in Visual C # through a specific example.

The example of this article is actually consisting of two parts, or it is also possible to be a client program and a server program. The client program function is passed

Socket creates a connection to the server program and sending data to the server after the connection is completed; the server program accepts the connection request of the network's socket, after the connection is complete, receive data sent from the client, and display come out. Let's first introduce Visual C # to implement the specific method of the client program by hosting socket.

Managed Visual C # Socket implementation method (a) (2) Author: Wang Tian dispatch time: 2003.11.19 II. 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 # Pay attention to the following issues when using Socket to transfer data: 1. Create a socket instance, create and 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. Switch the current window of Visual Studio .Net to the [Form1.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 void InitializeComponent () {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.te XtBox1.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 = "connection"; 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 = ""; this.listbox1.itemHeight = 12; this.listbox1.location = new system.drawing.point ( 20, 118); this.ListBox1.name = "ListBox1"; this.listbox1.size = new system.drawing.size (336, 160); this.listbox1.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 = "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, this.listbox1, this.textbox2, this.label2, this.button1, this.textbox1, this.label1, this .label3}; this.formo.forms.formorderstyle.Forms.FormBorderstyLle.FixedsingLE; this.maximizebox = false; this.name = "form1"; this.text = "Use socket to send data"; this.ResumeLayout (False }} To this [use sokcet to transfer data] The interface after the project is completed, as shown in Figure 01:

Figure 01: [Using Sokcet to send data] project design interface

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; // used to TcpListen class using System.Net;

Managed Visual C # Socket implementation method (a) (3) Author: Wang Tian dispatch time: 2003.11.19 6. Add the following code in the Form1 class code area, the following code is to define the role of global variables and create an instance of the use of global :

INT port = 8000; // Defines the listening port number private tclient tcpc; // Create a TCP connection private socket stset; / / Create a sending data socket private bool tcpConnect = false; // Define the identifier for use Indicates 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 to determine whether a successful connection and the remote endpoint try {stSend = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // initialize a Socket instance IPEndPoint tempRemoteIP = new IPEndPoint (IPAddress.Parse (textBox1.Text), port); // Create endPoint epTemp remote endpoint according to the IP address and port number = (endPoint) tempRemoteIP; stSend.Connect (epTemp); // connector The 8000 port number statusbar1.text = "successfully connected to the remote computer!"; TcpConnect = true; button1.enabled = false; button2.enabled = true;} catch (exception) {statusbar1.text = "target computer denied connection request ! ";}} 8. Replace the processing code corresponding to the Click event of the Button2 component in Form1.cs with the following code, the following code features the data to the remote host by using the Socket to transmit data to the remote host by the established connections.

Private void button2_click (object sender, system.eventargs e) {int neyngth = textBox2.text.length; // Get the length of the data to be sent byte [] bysend = new byte []l "; // Define one according to the length of the acquisition Byte type array bYsend = system.text.Encoding.default.getbytes; // Specify the string to the specified Byte array INT i = stsend.send (BYSEND) by specifying the encoding type. .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 recover resources:

Protected Override Void Dispose (Bool Disposing) {by (TcpConnect) {byte [] BYSEND = New Byte [4]; // Define byte array based on string "STOP" length. Default.Text.Encoding. Default.getbytes "Stop"); int i = stsend.send (bysend); // Send control code stsend.close (); // Close socket} if (disponents! = Null) {Components.dispose );}} Base.dispose (Disposing);} To this, after the above steps are executed correctly, [Use Socket to send data] All is completed.

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

New Post(0)