Guide to asynchronous server socket programming (Microsoft msdn)

Source: Internet
Author: User
Asynchronous Server sockets use the. NET Framework asynchronous programming model to process network service requests. The socket class follows the standard. NET Framework asynchronous naming mode. For example, the synchronous accept method corresponds to the asynchronous beginaccept and endaccept methods.
An Asynchronous Server socket needs a method to start accepting network connection requests, a callback method to process connection requests and start to receive network data, and a callback method to end receiving data. This section will further discuss all these methods.

In the following example, to start accepting network connection requests, initialize the socket using startlistening and start accepting new connections using beginaccept. When a new connection request is received on the socket, the callback method is called. It obtains the socket instance that will process the connection and submits the socket to the thread that will process the request. The callback method is used to implement asynccallback delegation. It returns void and carries a parameter of the iasyncresult type. The following example is the shell program that accepts the callback method.

[Visual Basic]

Sub acceptcallback (Ar as iasyncresult)
'Add the callback code here.
End sub 'acceptcallback

[C #]

Void acceptcallback (iasyncresult AR ){
// Add the callback code here.
}

The beginaccept method has two parameters: asynccallback delegate that accepts the callback method and an object that passes the status information to the callback method. In the following example, the listener socket passes the status parameter to the callback method. In this example, create an asynccallback delegate and begin to accept network connections.

[Visual Basic]

Listener. beginaccept (_
New asynccallback (socketlistener. acceptcallback ),_
Listener)

[C #]

Listener. beginaccept (
New asynccallback (socketlistener. acceptcallback ),
Listener );

Asynchronous sockets use threads in the system thread pool to process incoming connections. One thread is responsible for accepting connections, the other thread is used to process each incoming connection, and the other thread is responsible for receiving connection data. These threads can be the same thread, depending on the thread allocated by the thread pool. In the following example, The system. Threading. manualresetevent class suspends the execution of the main thread and sends a signal when the execution can continue.

The following example shows how to create an asynchronous TCP/IP socket on a local computer and start accepting connections. It assumes that there is a global manualresetevent named alldone. This method is a member of the class named socketlistener and defines a callback method named acceptcallback.

[Visual Basic]

Public sub startlistening ()
Dim iphostinfo as iphostentry = DNS. Resolve (DNS. gethostname ())
Dim localep = new ipendpoint (iphostinfo. Addresslist (0), 11000)

Console. writeline ("local address and port: {0}", localep. tostring ())

Dim listener as 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 (New _
Asynccallback (socketlistener. acceptcallback ),_
Listener)

Alldone. waitone ()
End while
Catch e as exception
Console. writeline (E. tostring ())
End try
Console. writeline ("Closing the listener ...")
End sub 'startlistening

[C #]

Public void startlistening (){
Iphostentry iphostinfo = 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 (
New asynccallback (socketlistener. acceptcallback ),
Listener );

Alldone. waitone ();
}
} Catch (exception e ){
Console. writeline (E. tostring ());
}

Console. writeline ("Closing the listener ...");
}

The accept callback method (acceptcallback in callback) sends a signal to the main application to continue processing, establish a connection with the client, and start to asynchronously read client data. The following example shows the first part of the acceptcallback method. This section of this method sends a signal to the main application thread for it to continue processing and establish a connection with the client. It uses a global manualresetevent named alldone.

[Visual Basic]

Public sub acceptcallback (Ar as iasyncresult)
Alldone. Set ()

Dim listener as socket = ctype (AR. asyncstate, socket)
Dim handler as socket = listener. endaccept (AR)

'Additional code to read data goes here.
End sub 'acceptcallback

[C #]

Public void acceptcallback (iasyncresult AR ){
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 status object that passes values between asynchronous calls. The following example implements a status object used to receive strings from a remote client. It contains the following fields: client socket, data buffer for receiving data, and stringbuilder used to create the data string sent by the client. Place these fields in the status object so that the values of these fields can be retained between multiple calls for data reading from the client socket.

[Visual Basic]

Public class stateobject
Public worksocket as socket = nothing
Public buffersize as integer = 1024
Public buffer (buffersize) as byte
Public Sb as new stringbuilder ()
End Class 'stateobject

[C #]

Public class stateobject {
Public socket worksocket = NULL;
Public const int buffersize = 1024;
Public byte [] buffer = new byte [buffersize];
Public stringbuilder sb = new stringbuilder ();
}

This section first initializes an instance of the stateobject class and calls the beginreceive method to start asynchronously reading data from the client socket.

The following example shows the complete acceptcallback method. It assumes that there is a manualresetevent named alldone, defines the stateobject class, and defines the readcallback method in the class named socketlistener.

[Visual Basic]

Public shared sub acceptcallback (Ar as iasyncresult)
'Get the socket that handles the client request.
Dim listener as socket = ctype (AR. asyncstate, socket)
Dim handler as socket = listener. endaccept (AR)

'Signal the main thread to continue.
Alldone. Set ()

'Create the State object.
Dim state as new stateobject ()
State. worksocket = Handler
Handler. beginreceive (State. buffer, 0, state. buffersize, 0 ,_
Addressof asynchronoussocketlistener. readcallback, state)
End sub 'acceptcallback

[C #]

Public static void acceptcallback (iasyncresult AR ){
// Get the socket that handles the client request.
Socket listener = (socket) Ar. asyncstate;
Socket handler = listener. endaccept (AR );

// Signal the main thread to continue.
Alldone. Set ();

// Create the State object.
Stateobject state = new stateobject ();
State. worksocket = handler;
Handler. beginreceive (State. buffer, 0, stateobject. buffersize, 0,
New asynccallback (asynchronoussocketlistener. readcallback), State );
}

The final method that needs to be implemented for the asynchronous socket server is the read callback method that returns the data sent by the client. Like the callback method, the read callback method is also an asynccallback delegate. This method reads one or more bytes from the client socket into the data buffer, and then calls the beginreceive method again until the data sent by the client is complete. After reading the entire message from the client, the console displays the string and closes the server socket that processes the connection with the client.

The following example implements the readcallback method. It defines the stateobject class.

[Visual Basic]

Public shared sub readcallback (Ar as iasyncresult)
Dim state as stateobject = ctype (AR. asyncstate, stateobject)
Dim handler as socket = state. worksocket

'Read data from the client socket.
Dim read as integer = handler. endreceive (AR)

'Data was read from the client socket.
If read> 0 then
State. sb. append (encoding. ASCII. getstring (State. buffer, 0, read ))
Handler. beginreceive (State. buffer, 0, state. buffersize, 0 ,_
Addressof readcallback, state)
Else
If State. sb. length> 1 then
'All the data has been read from the client;
'Display it on the console.
Dim content as string = state. sb. tostring ()
Console. writeline ("read {0} bytes from socket." + _
Controlchars. Cr + "data: {1}", content. length, content)
End if
End if
End sub 'readcallback

[C #]

Public void readcallback (iasyncresult AR ){
Stateobject state = (stateobject) Ar. asyncstate;
Socket handler = state. worksocket;

// Read data from the client socket.
Int READ = handler. endreceive (AR );

// Data was read from the client socket.
If (read> 0 ){
State. sb. append (encoding. ASCII. getstring (State. buffer, 0, read ));
Handler. beginreceive (State. buffer, 0, stateobject. buffersize, 0,
New asynccallback (readcallback), State );
} Else {
If (State. sb. length> 1 ){
// All the data has been read from the client;
// Display it on the console.
String content = state. sb. tostring ();
Console. writeline ("read {0} bytes from socket./n data: {1 }",
Content. length, content );
}
Handler. Close ();
}
}

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.