Http://community.9cbs.net/expert/topic/3410/3410381.xml?temp=.1048853
MS-help: //ms.msdnqtr.2003feb.2052/cpguide/html/cpconusingblockingserversocket.htm
Use synchronous server socket
Synchronous server sockets hang up the execution of the application until the connection request is received on the socket. Synchronous server sockets do not apply to applications that use the network in operation, but they may apply to simple web applications. Use the BIND and LISTEN methods to set up Socket to listen on the endpoint, Socket can use the Accept method at any time to accept the incoming connection request. The application is suspended until the connection request is received when the Accept method is called. When the connection request is received, the Accept returns a new Socket instance associated with the connection client. The following example reads the client data and displays the data on the console and then displays the data back to the client. Socket does not specify any message protocol, so the string "
Dim msg as byte () = encoding.ascii.getbytes (data) handler.send (msg) handler.shutdown (socketshutdown.both) handler.close () [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 ("
Console.writeLine ("Text Received: {0}", DATA);
Byte [] msg = encoding.ascii.getbytes (data); handler.send (msg); handler.shutdown (socketshutdown.both); handler.close ();
Use asynchronous server socket asynchronous server sockets to use .NET Framework asynchronous programming model to process network service requests. The Socket class follows the standard .NET Framework asynchronous naming mode; for example, synchronous accept methods correspond to asynchronous beaccept and endaccept methods. Asynchronous server socket requires a method of starting to accept network connection requests, a callback method that processes the connection request and starts receiving network data, and a callback method ending receiving data. This section will further discuss all of these methods. In the example below, to start accepting a network connection request, the method startListence initializes the socket and then use the BeginAccept method to start accepting a new connection. When the new connection request is received on the socket, the callback method will be called. It is responsible for obtaining the Socket instance that will handle the connection and submits the socket to the thread that will process the request. Accept the callback method to implement the AsyncCallback commission; it returns Void and takes an IASYNCRESULT type parameter. The following example is a housing program for receiving a 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} BeginAccept method takes two parameters: receiving points The AsyncCallback commission of the callback method and an object used to pass status information to the callback method. In the following example, the listening socket passes to the callback method through the status parameter. This example creates an AsyncCallBack delegate and starts accepting a network connection. [Visual Basic] listener.BeginAccept (_ New AsyncCallback (SocketListener.acceptCallback), _ listener) [C #] listener.BeginAccept (new AsyncCallback (SocketListener.acceptCallback), listener); threading asynchronous socket using the system thread pool Inferred connection. A thread is responsible for accepting the connection, and the other thread is used to handle each incoming connection, and a 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 example below, the System.Threading.manualRestEvent class hangs the execution of the main thread and signals when executing can continue. The following example shows the asynchronous method of creating an asynchronous TCP / IP socket on the local computer and starting to accept the connection. It assumes the following: There is a global manualReveTevent named Alldone, which is a member called SocketListener, and 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} ", localp.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 IP EndPoint (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); slisten (10); while (true) {alldone.reset (); console.writeline ("Waiting for a connection ..."); listener.BeginAccept (New asyncCallback (socketListener.acceptcallback, listener); alldone.waitone ();}} catch (e.tostring (E.TOString ());} console.writeline
Closing the listener ... ");} Accept the callback method (that is, the AcceptCallback in the precedent) is responsible for sending a signal to the primary application, letting it continue to process, establish a connection with the client and start reading the client data asynchronously. The example is the first part of the AcceptCallback method. This section is sent to the primary application thread to continue to process and establish a connection with the client. It adopts a global manualReveTevent, which is 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.ndAccept (ar); // additional code to read data goes here.} From the client sleeve Word read data requires a status object that transmits values between asynchronous calls. The following example implements a status object for receiving strings from a remote client. It contains the following fields: Client sleeve, use The data buffer receiving data, and StringBuilder for creating a data string sent by the client. Place these fields in the status object, so that the value of these fields is retained between multiple calls to be retained from the client Socket read data. [Visual Basic] Public Class StateObject Public Worksocket As Socket = Nothing Public Buffersize As Integer = 1024 Public Buffer (Buffersize) AS BYTE PUBL ic 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 begins to initialize an instance of the StateObject class, then call the BeginReceive method to begin reading data from the client socket. The following example shows a complete acceptcallback method. It assumes the following: there is a manualReveTevent named AlldOne, define the StateObject class, and define 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.Bu FFersize, 0, New asyncCallback (asynchronoussocketlistener.read (ASYNCALLBACK), STATE);} The FINAL method that needs to be implemented for the asynchronous socket server is the read callback method of the data sent by the client. Like the transfer method, reading the callback method is also an AsyncCallback commission. This method reads one or more bytes from the client socket to the data buffer, then call the BeginReceive method again until the data sent by the client is completed. After reading the entire message from the client, the string is displayed on the console and turn off the server socket that processs the connection to the client. The following example implements the REDCALLBACK method. It assumes that the StateObject class is defined.
[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 dam .sb.Append (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 ifnd sub 'readcallback [C #] Public Void ReadCallback (IasyncResult Ar ) {StateObject State = (stateObject) ar.asyncState; Socket H Andler = state.worksocket; // read data from the client socket. int = 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.buffness, 0, new asynccallback, state);} else {if (state.sb.length> 1) {// all the data haas 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 ();} Handler.close ();}} Use asynchronous client sleeve asynchronous client sleeve logging does not suspend the application when waiting for the network operation to complete. Instead, it uses standard .NET Framework asynchronous programming model to process network connections on a thread, and the application continues to run on the original thread. Asynchronous sockets apply to applications that use the network or to wait for network operations to complete. The Socket class follows the .NET Framework naming mode of the asynchronous method; for example, synchronous Receive method corresponds to an asynchronous BEGINRECEIVE and EndReceive method. Asynchronous operation requires a callback method to return the results. If the application does not need to know the result, no callback method is required. The code example in this section explains how to start connecting to the network device using a method and use a callback method to start sending data using a method and use a callback method to complete the send, and how to start receiving data using a method. The received data is ended using the callback method. Asynchronous sockets use a thread processing network connection in multiple system thread pools. A thread is responsible for initializing the transmission or reception of data; other threads complete the connection to the network device and transmit or receive data. In the following example, an instance of the System.Threading.manualReventEvent class is used to suspend the execution of the main thread and signal it can be issued. In the example below, in order to connect the asynchronous socket to the network device, the Connect method initializes a socket, then call the BegInnect method, pass the remote endpoint of the network device, connect the callback method, and the status object (ie client socket, with Transfer status information between asynchronous calls). This example implements the Connect method to connect the specified Socket to the specified endpoint. It uses a global manualReveTevent called ConnectDone. [Visual Basic] Public Shared Sub Connect (remoteEP As EndPoint, client As Socket) client.BeginConnect (remoteEP, _ AddressOf ConnectCallback, client) connectDone.WaitOne () End Sub 'Connect [C #] public static void Connect (EndPoint remoteEP, Socket Client) {Client.BegInConnect (Remoteep, New AsyncCallback, Client); ConnectDone.Waitone (); connection callback method ConnectCallback implements an AsyncCallback commission. It is connected to the remote device when the remote device is available, and then the signal is sent to the application thread by setting the ManualResetEvent ConnectDone. The following code implements the ConnectCallback method.
[Visual Basic] Private Shared Sub ConnectCallback (ar As IAsyncResult) Try 'Retrieve the socket from the state object. Dim client As Socket = CType (ar.AsyncState, Socket)' 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 e as exception console.writeline (E.TOSTRING ()) End Tryend Sub 'ConnectCallback [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 example method encodes the specified string data in the ASCII format and sends it to the network device represented by the specified socket. The following example implements the Send method.
[Visual Basic] Private Shared Sub Send (client As Socket, data As [String]) 'Convert the string data to byte data using ASCII encoding. Dim byteData As Byte () = Encoding.ASCII.GetBytes (data)' Begin sending the data to the remote device. client.BeginSend (byteData, 0, byteData.Length, SocketFlags.None, _ AddressOf SendCallback, client) End Sub 'Send [C #] private static void Send (Socket client, String data) {// Convert the string data to byte data 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, Client);} Send callback method SendCallback implements an AsyncCallback delegation. It sends data when the network device is ready to receive. The following example shows the implementation of the SendCallback method. It uses a global manualReveTevent called Senddone.
[Visual Basic] Private Shared Sub SendCallback (ar As IAsyncResult) Try 'Retrieve the socket from the state object. Dim client As Socket = CType (ar.AsyncState, Socket)' Complete sending the data to the remote device. Dim bytesSent As Integer = Client.Endsend (AR) Console.writeline ("SENT {0} Bytes to Server.", bytessent) 'Signal That Alltes Have Been Sent. Senddone.Set () Catch E AS Exception Console.Writeline (E.TOSTRING .)) End TryEnd Sub 'SendCallback [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 Int bytessent = client.ndsend (ar); console.writeline ("SENT {0} Bytes to Server.", bytessent); // signal That alltes Have been Sent. Senddone.set ();} catch (Exception e) {console.writeline (e.tostring ()); } The read data from the client socket requires a status object that transmits a value between asynchronous calls. The following class is an example state object for receiving data from the client sleeve. It contains the following fields: client sleeve, buffer for receiving data, and StringBuilder for saving incoming data strings. Place these fields in this status object so that the values of these fields are reserved between multiple calls to read data from the client sleeve.
[Visual Basic] Public Class StateObject 'Client socket. Public workSocket As Socket = Nothing' Size of receive buffer. Public BufferSize As Integer = 256 'Receive buffer. Public buffer (256) As Byte' Received data string. Public sb As New StringBuilder () End class' stateObject [C #] public class stateObject {// Client socket public Socket workSocket = null;.. // Size of receive buffer public const int BufferSize = 256;. // Receive buffer public byte [] buffer = new Byte [buffersize]; // receivebuilder sb = new stringbuilder ();} Receive method example sets the status object, and then call the BeginReceive method to read data from the client socket. The following example implements the Receive method. [Visual Basic] Private Shared Sub Receive (client As Socket) Try 'Create the state object. Dim state As New StateObject () state.workSocket = client' Begin receiving the data from the remote device. Client.BeginReceive (state.buffer, 0, state.BufferSize, 0, _ AddressOf ReceiveCallback, state) Catch e As Exception Console.WriteLine (e.ToString ()) End TryEnd Sub 'Receive [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 implements an AsyncCallback commission. It receives data from the network device and generates a message string.
It reads one or more data bytes from the network into the data buffer, then call the BeginReceive method again until the data sent by the client is completed. After reading all the data from the client, ReceiveCallback passes the signal to the application thread by setting the ManualReveTevent Senddone. The sample code below implements the ReceiveCallback method. It uses a global string called Response, which contains the received string and a global manualReveTevent called ReceiveDone. The server must completely shut down the client socket to end the network session.
[Visual Basic] Private Shared Sub ReceiveCallback (ar As IAsyncResult) Try 'Retrieve the state object and the client socket' from the asynchronous state object. Dim state As StateObject = CType (ar.AsyncState, StateObject) Dim client As Socket = state. workSocket 'Read data from the remote device. Dim bytesRead As Integer = client.EndReceive (ar) If bytesRead> 0 Then' There might be more data, 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, state.BufferSize, 0, _ AddressOf ReceiveCallback, state) Else' All the data has arrived; Put it in response. if state.sb.length> 1 Then response = state.sb.tostring () Endness () Endness () Endness () Endness () end bytes have been receiving. REC eiveDone.Set () End If Catch e As Exception Console.WriteLine (e.ToString ()) End TryEnd Sub 'ReceiveCallback [C #] private static void ReceiveCallback (IAsyncResult ar) {try {// Retrieve the state object and the client socket . // from the asynchronous 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 Be More Data, So Store The Data Received So Far. State.Sb.Append (Encoding.ASCII.GetString (state.buffer, 0, bytesread);