Winform Learning Log (21) ------ Socket (TCP) client request and server listener and link BASICS (example)

Source: Internet
Author: User

I. Basic Knowledge review I:

Socket

Implement the Berkeley socket interface.

Socket (AddressFamily, SocketType, ProtocolType)

Uses the specified address family, Socket type, and Protocol to initialize

New instance.

 

Bind associates the Socket with a local endpoint.

Listen places the Socket in the listening state.

Accept creates a new Socket for the new connection.

 

II:

Socket. Bind Method

Associate the Socket with a local endpoint.

Type: System. Net. EndPoint

The local EndPoint to be associated with the Socket.

To use a specific local endpoint, use the Bind method. Bind must be called before the Listen method can be called. Unless a specific

Local endpoint. Otherwise, you do not have to call Bind before using the Connect method. You can use the Bind method for connectionless and connection-oriented protocols.

 

Before calling a Bind, you must first create a local IPEndPoint from which data is to be communicated. If you do not mind which local address to allocate, you can use

IPAddress. Any is used as the address parameter to create an IPEndPoint. In this way, the basic service provider allocates the most suitable network address. If you have multiple

Network interface, which helps simplify your applications. If you do not mind which local port to use, you can create

IPEndPoint. In this case, the service provider assigns an available port number (between 1024 and 5000 ).

 

If you use the preceding method, you can call LocalEndPoint to obtain the allocated local network address and port number. If you are currently using connection-oriented

After you call the Connect or EndConnect method, LocalEndPoint returns the locally allocated network address. If you are using

Is a non-connection protocol, it is not accessible until a sending or receiving operation is completed.

 

If UDP socket needs to obtain interface information about received data packets, it should explicitly call the SetSocketOption method and socket option

PacketInformation after the Bind method.

 

If you want to receive multicast data packets, you must use the multicast port number to call the Bind method.

 

If you want to use the ReceiveFrom method to receive connectionless datagram, you must call the Bind method.

 

If you receive SocketException when calling the Bind method, you can use the SocketException. ErrorCode attribute to obtain the specific error code.

. After obtaining this code, you can refer to the Windows Sockets 2nd API error code document in the MSDN Library to obtain the error

.

 

When network tracing is enabled in the application, this member outputs the tracing information.

 

III:

Socket. Listen Method

Place the Socket in the listening state.

 

Parameters

Backlog

Type: System. Int32

Maximum length of the suspended connection queue.

 

Listen allows a connection-oriented Socket to Listen for incoming connection attempts. The backlog parameter specifies the maximum number of incoming connections that can be accommodated in the queue.

Number. To determine the maximum number of connections that can be specified, retrieve the MaxConnections value. Listen does not stop.

 

If SocketException is received, use the ErrorCode attribute to obtain the specific error code. After obtaining this code, you can refer to the MSDN Library

For more information about the error code. You can use Accept or BeginAccept to Accept

The connection from the queue.

 

Before calling Listen, you must first call the Bind method. Otherwise, Listen will cause SocketException.

 

When network tracing is enabled in the application, this member outputs the tracing information.

 

Depending on the operating system, the backlog parameters are limited to different values. You can specify a larger value, but the backlog will be restricted by the operating system.

IV:

Socket. Accept Method

Create a new Socket for the new connection.

Return Value

Type: System. Net. Sockets. Socket

Create a connection Socket.

The Accept extracts the first pending connection request from the connection request queue of the listening Socket synchronously, and then creates and returns the new Socket. Return is unavailable.

The returned Socket accepts any additional connections in the connection queue. However, you can call the RemoteEndPoint method of the returned Socket to identify the remote master.

The network address and port number of the server.

In blocking mode, Accept remains in the blocking status until incoming connection attempts are queued. After the connection is accepted, the original Socket will continue to be passed in

The connection request is queued until you close it.

If you use a non-blocking Socket to call this method, and the queue does not have a connection request, Accept will cause SocketException. If you receive

SocketException. Use the SocketException. ErrorCode attribute to obtain the specific error code. After obtaining this code, you can refer to MSDN

For more information about the API error code documentation for Windows Sockets 2nd in the Library.

Before calling the Accept method, you must first call the Listen method to Listen for incoming connection requests and put the requests to the queue.

When network tracing is enabled in the application, this member outputs the tracing information.

V:

ThreadStart delegate

Indicates the method executed on the Thread.

When a managed Thread is created, the method executed on the Thread will be passed to the Thread constructor through a ThreadStart delegate or

ParameterizedThreadStart delegate. Before calling the Thread. Start method, the Thread will not Start execution. The execution will start from ThreadStart

Or the first line of the method represented by the ParameterizedThreadStart delegate.

Visual Basic and C # You can omit the ThreadStart or ParameterizedThreadStart Delegate constructor when creating a thread. In the Visual

In Basic, The AddressOf operator is used when the method is passed to the Thread constructor, for example, Dim t As New Thread (AddressOf

ThreadProc ). In C #, you only need to specify the name of the thread process. The compiler selects the correct Delegate constructor.

In the. NET Framework of Version 2.0, only one parameter is required to create a ThreadStart delegate for the static method in C ++: the address of the callback method (

Class Name ). In earlier versions, two parameters are required to create a delegate for a static method: zero (null) and method address. For instance methods, all versions require

Two parameters are required: instance variables and method addresses.

Class Test

{

Static void Main ()

{

// To start a thread using a static thread procedure, use

// Class name and method name when you create the ThreadStart

// Delegate. Beginning in version 2.0 of the. NET Framework,

// It is not necessary to create a delegate explicitly.

// Specify the name of the method in the Thread constructor,

// And the compiler selects the correct delegate. For example:

//

// Thread newThread = new Thread (Work. DoWork );

//

ThreadStart threadDelegate = new ThreadStart (Work. DoWork );

Thread newThread = new Thread (threadDelegate );

NewThread. Start ();

// To start a thread using an instance method for the thread

// Procedure, use the instance variable and method name when

// You create the ThreadStart delegate. Beginning in version

// 2.0 of the. NET Framework, the explicit delegate is not

// Required.

//

Work w = new Work ();

W. Data = 42;

ThreadDelegate = new ThreadStart (w. DoMoreWork );

NewThread = new Thread (threadDelegate );

NewThread. Start ();

}

}

Class Work

{

Public static void DoWork ()

{

Console. WriteLine ("Static thread procedure .");

}

Public int Data;

Public void DoMoreWork ()

{

Console. WriteLine ("Instance thread procedure. Data = {0}", Data );

}

}

VI:

Control. InvokeRequired attributes

Gets a value that indicates whether the caller must call the Invoke method when calling the method of the control, because the call orientation is outside the thread where the control is created

.

Attribute Value

Type: System. Boolean

If the Handle of the control is created on a thread different from the call thread (it indicates that you must call the control through the Invoke method), it is true; no

It is false.

Implementation

ISynchronizeInvoke. InvokeRequired

 

Controls in Windows Forms are bound to specific threads and do not have thread security. Therefore, if you call the control method from another thread, you must

Use the Invoke method of the control to mail the call to the appropriate thread. This attribute can be used to determine whether the Invoke method must be called.

This is useful when you have controls.

If you have created a control handle, in addition to the InvokeRequired property, the control has four methods that can be safely called from any thread.

Yes: Invoke, BeginInvoke, EndInvoke, and CreateGraphics. Call CreateGraphics before creating a control handle on the background thread

This may cause invalid cross-thread calls. For all other method calls, use one of these Invoke methods when calling from another thread.

If the control handle does not exist, InvokeRequired searches along the control's parent chain until it finds the control or form with a window handle. If no

The InvokeRequired method returns false.

This means that if Invoke is not required (the call occurs on the same thread), or if the control is created on another thread but has not yet created a control handle

InvokeRequired can return false.

If you have not created a control handle, you cannot simply call properties, methods, or events on the control. This may lead to the creation of the control handle on the background thread, from

The controls on threads without message pump are isolated and the application is unstable.

When InvokeRequired returns false in the background thread, you can also avoid this situation by checking the IsHandleCreated value. If you have not created

Create a control handle. You must wait until the control handle has been created before you can call Invoke or BeginInvoke. Generally, only when in the constructor of the main form of the application

When a background thread is created (as in Application. Run (new MainForm (), it is created before the form is displayed or Application. Run is canceled.

This happens.

One solution is to wait until the form handle has been created and then start the background thread. You can call the Handle attribute to forcibly create a Handle or wait for the Load

To start the background process.

. NET Framework 4.5 0 (3 in total) is helpful for the evaluation of this Article

[BrowsableAttribute (false)]

Public bool InvokeRequired {get ;}

C #

Add Community resources

A better solution is to use SynchronizationContext returned by SynchronizationContext instead of using controls for inter-thread Blocking

Processing.

If the thread to process the message is no longer active, an exception may occur.

7:

Control. Invoke Method

Execute the delegate on the thread that owns the basic window handle of this control.

Invoke (Delegate) executes the specified Delegate on the thread that owns the basic window handle of this control.

Invoke (Delegate, Object []) executes the specified Delegate with the specified parameter list on the thread that owns the basic window handle of the control.

8:

Control. Invoke method (Delegate, Object [])

Run the specified delegate with the specified parameter list on the thread that owns the basic window handle of the control.

Parameters

Method

Type: System. Delegate

The number and type of parameters used by a method delegate are the same as those contained in The args parameter.

Args

Type: System. Object []

Array of objects passed as parameters of the specified method. If this method does not have a parameter, this parameter can be null.

Return Value

Type: System. Object

Object, which contains the delegate return value being called. If the delegate does not return a value, it is null.

Implementation

ISynchronizeInvoke. Invoke (Delegate, Object [])

 

A delegate is similar to a function pointer in C or C ++. The delegate encapsulates the reference to the method in the delegate object. You can then pass the delegate object to

The code of the method used, and the method to be called at compilation can be unknown. Unlike function pointers in C or C ++, delegation is object-oriented and class

And more secure.

If the control handle does not exist, this method searches along the control's parent chain until it finds a control or form with a window handle. If no appropriate sentence is found

Handle. This method causes an exception. Exceptions thrown during the call process will be propagated back to the caller.

If you have created a control handle, in addition to the InvokeRequired property, the control has four methods that can be safely called from any thread.

Yes: Invoke, BeginInvoke, EndInvoke, and CreateGraphics. Call CreateGraphics before creating a control handle on the background thread

This may cause invalid cross-thread calls. For all other method calls, use one of the Call (invoke) Methods to block calls to the control thread.

The delegate can be an EventHandler instance. In this case, the sender parameter will include this control, and the event parameter will include EventArgs. Empty. Delegate return

It can be a MethodInvoker instance or any other delegate that uses the void parameter list. Call EventHandler or MethodInvoker for delegate comparison

Other types of delegation are faster.

If the thread to process the message is no longer active, an exception may occur.

IX:

Socket. Connect Method
Establish a connection with the remote host.
Connect (EndPoint) establishes a connection with the remote host.
Socket. Connect Method (EndPoint)
Establish a connection with the remote host.
Parameters
RemoteEP
Type: System. Net. EndPoint
EndPoint, indicating a remote device.
If you are using a connection-oriented protocol (such as TCP), the Connect method establishes a network between the LocalEndPoint and the specified remote endpoint synchronously.
Connection. If you are using a non-connection protocol, Connect creates a default remote host. After Connect is called, use the Send method
Send data to a remote device, or use the Receive method to Receive data from a remote device.
If you are using a connectionless protocol (such as UDP), you do not have to call Connect to send and receive data first. You can use SendTo and
ReceiveFrom to communicate with the remote host synchronously. If you call Connect, any address other than the specified default address will be discarded.
Datagram. To set the default remote host as a broadcast address, you must first call the SetSocketOption method and set the socket option
SocketOptionName. Broadcast; otherwise, Connect will cause SocketException. If you receive SocketException, use
The SocketException. ErrorCode attribute gets the specific error code.
The Connect method will be blocked unless the Blocking attribute has been specifically set to false before you call Connect. If you are currently using
Connection protocol (such as TCP), and block is indeed disabled, Connect will cause SocketException, because it takes a while to establish a connection
. Without the connection protocol, no exception is thrown, because they only need to create a default remote host. You can use SocketException. ErrorCode to obtain
Specific error code. After obtaining this code, you can refer to the Windows Sockets 2nd API error code document in the MSDN Library to obtain
Detailed description of the error. If WSAEWOULDBLOCK is returned for an error, it indicates that the remote host connection has been initialized by the connection-oriented Socket,
Failed. You can use the Poll method to determine when the Socket completes the connection.
If the connection-oriented protocol is used and Bind is not called before Connect is called, the basic service provider will allocate a local network
Address and port number. If no connection protocol is used, the service provider allocates a local network location only when the sending or receiving operation is complete.
Address and port number. If you want to change the default remote host, use the endpoint to call Connect again.
If the socket has been disconnected, you cannot use this method to restore the connection. Use one of the inconnect asynchronous methods to reconnect. This is the foundation
A restriction on the provider.
When network tracing is enabled in the application, this member outputs the tracing information.

Ii. Example,

B. Server Side
  = =            SetText(                             btn_StartServer_Click(                        sck =             IPAddress ip =            IPEndPoint endPoint =  IPEndPoint(ip,             sck.Listen(            ThreadStart threadDelegate =  ThreadStart(            newthread =             newthread.IsBackground =          ShowMsg( (                SetText d = .Invoke(d,   Ystr =  (tb_infor.Text != = tb_infor.Text + .tb_infor.Text = Ystr +             Socket accSck =            ShowMsg(
C. Client
  = =                                       btn_login_Click(=             IPAddress ip == 
3. Error,

Solution: Use InvokeRequired to determine whether the Invoke processing thread delegates B,


Solution:

// Set the SOCKET to allow multiple sockets to access the same local IP address and port number
Sck. SetSocketOption (SocketOptionLevel. Socket, SocketOptionName. ReuseAddress, true );

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.