Use. NET access to the Internet (4) Paul

Source: Internet
Author: User
Tags bind execution implement connect socket thread tostring port number

Using asynchronous client sockets


Asynchronous client sockets do not suspend the application while waiting for the network operation to complete. Instead, it uses the standard. NET framework asynchronous programming model to handle network connections on one thread, and the application continues to run on the original thread. Asynchronous sockets apply to applications that use a large network or do not wait for network operations to complete to continue.
The Socket class follows the. NET framework naming pattern of the asynchronous method; For example, the synchronous Receive method corresponds to the asynchronous BeginReceive and EndReceive methods.
The asynchronous operation requires the callback method to return the result of the operation. If the application does not need to know the result, no callback method is required. The code examples in this section illustrate how to use a method to start a connection with a network device and end a connection with a callback method, use a method to start sending data and use a callback method to finish sending, and how to use a method to start receiving data and use a callback method to end receiving data.
Asynchronous sockets use threads in multiple system thread pools to handle network connections. A thread is responsible for initializing the sending or receiving of data, and other threads are connecting to the network device and sending or receiving data. In the following example, an instance of the System.Threading.ManualResetEvent class is used to suspend execution of the main thread and send a signal when execution can continue.
In the following example, the Connect method initializes to connect an asynchronous socket to a network device. Socketinstance, and then calls the BeginConnect method, passing the remote endpoint representing the network device, the connection callback method, and the state object (that is, the client Socketinstance, which is used to pass state information between asynchronous invocations. This example implements the Connect method to place the specified SocketThe instance is connected to the specified endpoint. It assumes that there is a global with the name Connectdone ManualResetEvent
[C #]
public static void Connect (EndPoint remoteep, Socket client) {
New AsyncCallback (Connectcallback), client);
Connectdone.waitone ();
}

The connection callback method Connectcallback implement the AsyncCallback delegate. It connects to a remote device when a remote device is available, and then sets the ManualResetEventConnectdone sends a signal to the application thread that the connection is complete. The following code implements the Connectcallback method.
[C #]
private static void Connectcallback (IAsyncResult ar) {
try {
Retrieve the socket from the state object.
Socket client = (socket) ar. asyncstate;
Complete the connection.
Client. EndConnect (AR);
Console.WriteLine ("Socket connected to {0}",
Client. Remoteendpoint.tostring ());
Signal that the connection has been made.
Connectdone.set ();
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}

The Send sample method encodes the specified string data in ASCII format and sends it asynchronously to the network device represented by the specified socket. The following example implements the Send method.
[C #]
private static void Send (Socket client, String data) {
Convert the string data to byte using ASCII encoding.
byte[] Bytedata = Encoding.ASCII.GetBytes (data);
Begin sending the data to the remote device.
Client. BeginSend (bytedata, 0, Bytedata.length, Socketflags.none,
New AsyncCallback (Sendcallback), client);
}

Send callback method Sendcallback implement AsyncCallback delegate. It sends data when a network device is ready to receive. The following example shows the implementation of the Sendcallback method. It assumes that there is a global with the name Senddone ManualResetEventInstance.
[C #]
private static void Sendcallback (IAsyncResult ar) {
try {
Retrieve the socket from the state object.
Socket client = (socket) ar. asyncstate;
Complete sending the data to the remote device.
int bytessent = client. Endsend (AR);
Console.WriteLine ("Sent {0} bytes to server.", bytessent);
Signal that all bytes have been sent.
Senddone.set ();
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}

Reading data from a client socket requires a state object that passes a value between asynchronous invocations. The following class is a sample state object that is used to receive data from a client socket. It contains fields such as a client socket, a buffer for receiving data, and a StringBuilder for saving incoming data strings. Place these fields in the state object so that the values of those fields are retained between multiple invocations to read data from the client socket.
[C #]
public class StateObject {
Public Socket worksocket = null; Client socket.
public const int buffersize = 256; Size of receive buffer.
Public byte[] buffer = new Byte[buffersize]; Receive buffer.
Public StringBuilder sb = new StringBuilder ();//Received data string.
}

The Receive Method Example sets the state object and then calls the BeginReceivemethod to read data asynchronously from a client socket. The following example implements the Receive method.
[C #]
private static void Receive (Socket client) {
try {
Create the state object.
StateObject state = new StateObject ();
State.worksocket = client;
Begin receiving the data from the remote device.
Client. BeginReceive (state.buffer, 0, stateobject.buffersize, 0,
New AsyncCallback (ReceiveCallback), state);
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}

Receive callback method ReceiveCallback implementation AsyncCallbackCommissioned. It receives data from a network device and generates a message string. It reads one or more data bytes from the network into the data buffer, and then calls the BeginReceiveMethod until the data sent by the client is complete. After all data is read from the client, receivecallback by setting ManualResetEventSenddone signals the completion of data to the application thread.
The following example code implements the ReceiveCallback method. It assumes the existence of a global string named response (the string that holds the received string) and a global of the name Receivedone ManualResetEventInstance. The server must shut down the client socket gracefully to end the network session.
[C #]
private static void ReceiveCallback (IAsyncResult ar) {
try {
From the async state object.
StateObject state = (stateobject) ar. asyncstate;
Socket client = State.worksocket;
Read data from the remote device.
int bytesread = client. EndReceive (AR);
if (Bytesread > 0) {
There might is more data, and so store the "data received so far."
State.sb.Append (Encoding.ASCII.GetString (State.buffer,0,bytesread));
Get the rest of the data.
Client. BeginReceive (state.buffer,0,stateobject.buffersize,0,
New AsyncCallback (ReceiveCallback), state);
} else {
All the data has arrived; Put it in response.
if (State.sb.Length > 1) {
Response = state.sb.ToString ();
}
Signal that all bytes have been received.
Receivedone.set ();
}
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}

Listening with sockets


The listener or server socket opens a port on the network and waits for the client to connect to the port. Although there are other network address families and protocols, this example shows how to create a remote service for a TCP/IP network.
The unique address of the TCP/IP service is defined by combining the IP address of the host with the port number of the service to create an endpoint for the service. The Dns class provides methods that return information about the network addresses supported by the local network device. When a local network device has more than one network address, or when a local system supports multiple network devices, DnsClass returns information about all network addresses, the application must select the correct address for the service. The Internet Allocation number Authority (Internet assigned Numbers Authority, IANA) defines the port number of the public service (for more information, visit the http://www.iana.org/assignments/ Port-numbers). Other services can have a registration port number in the range of 1,024 to 65,535.
The following code example passes the DnsThe first IP address returned by the main machine is combined with the port number selected from the range of the register port number to create a ipendpoint for the server.
[C #]
Iphostentry iphostinfo = Dns.resolve (Dns.gethostname ());
IPAddress ipaddress = iphostinfo.addresslist[0];
IPEndPoint localendpoint = new IPEndPoint (ipaddress, 11000);

After you determine the local endpoint, you must use the Bind method to associate the Socket with the endpoint and use the Listen method to set the SocketListens on the endpoint. If a particular address and port combination is already in use, the BindThrows an exception. The following example illustrates how to set the SocketAnd IPEndPointAssociation.
[C #]
Listener. Bind (Localendpoint);
Listener. Listen (100);

ListenMethod with a single parameter that specifies the permission that is allowed before the connection client is returned to the server for a busy error SocketNumber of pending connections. In this example, you can place up to 100 clients in the connection queue before returning a server busy response to a 101th client.

Using Synchronization server sockets


The synchronization server socket suspends execution of the application until a connection request is received on the socket. Synchronization server sockets do not apply to applications that use a large number of networks in operations, but they may be appropriate for simple network applications.
After you use the Bind and Listen methods to set the Socket to listen on the endpoint, SocketYou can use the Accept method to accept incoming connection requests at any time. The application is suspended until the call to Acceptmethod receives a connection request.
When a connection request is received, AcceptReturns an association with the connection client for a new SocketInstance. The following example reads the client data, displays the data on the console, and then echoes the data back to the client. SocketNo message protocol is specified, so the string "<EOF>" marks the end of the message data. It's falsely named listener. SocketThe instance is initialized and bound to the endpoint.
[C #]
Console.WriteLine ("Waiting for a Connection ...");
Socket handler = listener. Accept ();
String data = null;
while (true) {
bytes = new byte[1024];
int Bytesrec = handler. Receive (bytes);
Data + + Encoding.ASCII.GetString (BYTES,0,BYTESREC);
if (data. IndexOf ("<EOF>") >-1) {
Break
}
}
Console.WriteLine ("Text Received: {0}", data);
byte[] msg = Encoding.ASCII.GetBytes (data);
Handler. Send (msg);
Handler. Shutdown (Socketshutdown.both);
Handler. Close ();

Using asynchronous server sockets


Asynchronous server sockets use the. NET framework asynchronous programming model to process Network Service requests. The Socket class follows the standard. NET asynchronous naming pattern, for example, the synchronous Accept method corresponds to the asynchronous BeginAccept and Endaccept methods.
Asynchronous server sockets require a method to begin accepting requests for network connections, a callback method that handles connection requests and begins to receive network data, and a callback method that ends receiving data. All of these methods are discussed further in this section.
In the following example, the method startlistening is initialized to begin accepting a network connection request. Socket, and then use beginacceptmethod to begin accepting a new connection. Invokes the accept callback method when a new connection request is received on a socket. It is responsible for getting the connection that will handle the Socketinstance, and the SocketSubmitted to the thread that will process the request. Accept the callback method to implement the AsyncCallback delegate; it returns void and takes a IAsyncResult type parameter. The following example is the shell that accepts the callback method.
[C #]
void Acceptcallback (IAsyncResult ar) {
ADD the callback code here.
}

beginacceptMethod with two parameters: pointer to the method that accepts the callback AsyncCallbackDelegate and an object that is used to pass state information to the callback method. In the following example, listening for SocketPass Stateparameter is passed to the callback method. This example creates a AsyncCallbackDelegate and begin accepting network connections.
[C #]
Listener. BeginAccept (
Listener);

Asynchronous sockets use threads in the system's thread pool to handle incoming connections. One thread is responsible for accepting the connection, another thread is used to process each incoming connection, and one is responsible for receiving the connection data. These threads can be the same thread, depending on which thread is assigned by the thread pool. In the following example, the System.Threading.ManualResetEvent class suspends execution of the main thread and emits a signal when execution can continue.
The following example shows an asynchronous method that creates an asynchronous TCP/IP socket on the local computer and begins to accept the connection. It assumes the following: There is a global with the name Alldone ManualResetEventinstance, which is a member of the SocketListener class, and a callback method named Acceptcallback is defined.
[C #]
public void startlistening () {
Iphostentry iphostinfo = new Dns.resolve (Dns.gethostname ());
IPEndPoint localEP = new IPEndPoint (iphostinfo.addresslist[0],11000);
Console.WriteLine ("Local address and port: {0}", localep.tostring ());
Socket listener = new Socket (localEP.Address.AddressFamily,
SocketType.Stream, PROTOCOLTYPE.TCP);
try {
Listener. Bind (LOCALEP);
S.listen (10);
while (true) {
Alldone.reset ();
Console.WriteLine ("Waiting for a Connection ...");
Listener. BeginAccept (
Listener);
Alldone.waitone ();
}
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
Console.WriteLine ("Closing The Listener ...");
}

Accepting the callback method (the Acceptcallback in the previous precedent) is responsible for signaling the main application to continue processing, establish a connection to the client, and begin to read the client data asynchronously. The following example is the first part of the Acceptcallback method implementation. This section of the method signals the main application thread to continue processing and establish a connection to the client. It assumes that there is a global with the name Alldone ManualResetEventInstance.
[C #]
public void Acceptcallback (IAsyncResult ac) {
Alldone.set ();
Socket listener = (socket) ar. asyncstate;
Socket handler = listener. Endaccept (AR);
Additional code to read data goes here.
}

Reading data from a client socket requires a state object that passes a value between asynchronous invocations. The following example implements a state object that is used to receive a string from a remote client. It contains fields such as a client socket, a data buffer for receiving data, and a StringBuilder for creating a data string sent by the client. Place these fields in the state object so that the values of those fields are retained between multiple invocations to read data from the client socket.
[C #]
public class StateObject {
Public Socket worksocket = null;
public const int buffersize = 1024;
Public byte[] buffer = new Byte[buffersize];
Public StringBuilder sb = new StringBuilder ();
<>




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.