使用異步客戶端套接字
異步客戶端套接字在等待網絡操作完成時不掛起應用程序。相反,它使用標準 .NET 框架異步編程模型在一個線程上處理網絡連接,而應用程序繼續在原始線程上運行。異步套接字適用于大量使用網絡或不能等待網絡操作完成才能繼續的應用程序。
Socket 類遵循異步方法的 .NET 框架命名模式;例如,同步 Receive 方法對應異步 BeginReceive 和 EndReceive 方法。
異步操作要求回調方法返回操作結果。如果應用程序不需要知道結果,則不需要任何回調方法。本節中的代碼示例闡釋如何使用某個方法開始與網絡設備的連接并使用回調方法結束連接,如何使用某個方法開始發送數據并使用回調方法完成發送,以及如何使用某個方法開始接收數據并使用回調方法結束接收數據。
異步套接字使用多個系統線程池中的線程處理網絡連接。一個線程負責初始化數據的發送或接收;其他線程完成與網絡設備的連接并發送或接收數據。在下列示例中,System.Threading.ManualResetEvent 類的實例用于掛起主線程的執行并在執行可以繼續時發出信號。
在下面的示例中,為了將異步套接字連接到網絡設備,Connect
方法初始化 Socket 實例,然后調用 BeginConnect 方法,傳遞表示網絡設備的遠程終結點、連接回調方法以及狀態對象(即客戶端 Socket 實例,用于在異步調用之間傳遞狀態信息)。該示例實現 Connect
方法以將指定的 Socket 實例連接到指定的終結點。它假定存在一個名為 connectDone
的全局 ManualResetEvent。
[C#]
public static void Connect(EndPoint remoteEP, Socket client) {
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client );
connectDone.WaitOne();
}
連接回調方法 ConnectCallback
實現 AsyncCallback 委托。它在遠程設備可用時連接到遠程設備,然后通過設置 ManualResetEvent connectDone
向應用程序線程發出連接完成的信號。下面的代碼實現 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());
}
}
Send
示例方法以 ASCII 格式對指定的字符串數據進行編碼,并將其異步發送到指定的套接字所表示的網絡設備。下面的示例實現 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(SendCallback), client);
}
發送回調方法 SendCallback
實現 AsyncCallback 委托。它在網絡設備準備接收時發送數據。下面的示例顯示 SendCallback
方法的實現。它假定存在一個名為 sendDone
的全局 ManualResetEvent 實例。
[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());
}
}
從客戶端套接字讀取數據需要一個在異步調用之間傳遞值的狀態對象。下面的類是用于從客戶端套接字接收數據的示例狀態對象。它包含以下各項的字段:客戶端套接字,用于接收數據的緩沖區,以及用于保存傳入數據字符串的 StringBuilder。將這些字段放在該狀態對象中,使這些字段的值在多個調用之間得以保留,以便從客戶端套接字讀取數據。
[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.
}
Receive
方法示例設置狀態對象,然后調用 BeginReceive 方法從客戶端套接字異步讀取數據。下面的示例實現 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());
}
}
接收回調方法 ReceiveCallback
實現 AsyncCallback 委托。它接收來自網絡設備的數據并生成消息字符串。它將來自網絡的一個或多個數據字節讀入數據緩沖區,然后再次調用 BeginReceive 方法,直到客戶端發送的數據完成為止。從客戶端讀取所有數據后,ReceiveCallback
通過設置 ManualResetEvent sendDone
向應用程序線程發出數據完成的信號。
下面的示例代碼實現 ReceiveCallback
方法。它假定存在一個名為 response
的全局字符串(該字符串保存接收的字符串)和一個名為 receiveDone
的全局 ManualResetEvent 實例。服務器必須正常關閉客戶端套接字以結束網絡會話。
[C#]
private static void ReceiveCallback( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// 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 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,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());
}
}
用套接字進行偵聽
偵聽器或服務器套接字在網絡上打開一個端口,然后等待客戶端連接到該端口。盡管存在其他網絡地址族和協議,但本示例說明如何為 TCP/IP 網絡創建遠程服務。
TCP/IP 服務的唯一地址是這樣定義的:將主機的 IP 地址與服務的端口號組合,以便為服務創建終結點。Dns 類提供的方法返回有關本地網絡設備支持的網絡地址的信息。當本地網絡設備有多個網絡地址時,或者當本地系統支持多個網絡設備時,Dns 類返回有關所有網絡地址的信息,應用程序必須為服務選擇正確的地址。Internet 分配號碼機構 (Internet Assigned Numbers Authority, IANA) 定義公共服務的端口號(有關更多信息,請訪問 http://www.iana.org/assignments/port-numbers)。其他服務可以具有 1,024 到 65,535 范圍內的注冊端口號。
下面的代碼示例通過將 Dns 為主機返回的第一個 IP 地址與從注冊端口號范圍內選擇的端口號組合,為服務器創建 IPEndPoint。
[C#]
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
確定本地終結點后,必須使用 Bind 方法將 Socket 與該終結點關聯,并使用 Listen 方法設置 Socket 在該終結點上偵聽。如果特定的地址和端口組合已經被使用,則 Bind 將引發異常。下面的示例闡釋如何將 Socket 與 IPEndPoint 關聯。
[C#]
listener.Bind(localEndPoint);
listener.Listen(100);
Listen 方法帶單個參數,該參數指定在向連接客戶端返回服務器忙錯誤之前允許的 Socket 掛起連接數。在本示例中,在向第 101 個客戶端返回服務器忙響應之前,最多可以在連接隊列中放置 100 個客戶端。
使用同步服務器套接字
同步服務器套接字掛起應用程序的執行,直到套接字上接收到連接請求。同步服務器套接字不適用于在操作中大量使用網絡的應用程序,但它們可能適用于簡單的網絡應用程序。
使用 Bind 和 Listen 方法設置 Socket 以在終結點上偵聽之后,Socket 就可以隨時使用 Accept 方法接受傳入的連接請求了。應用程序被掛起,直到調用 Accept 方法時接收到連接請求。
接收到連接請求時,Accept 返回一個與連接客戶端關聯的新 Socket 實例。下面的示例讀取客戶端數據,在控制臺上顯示該數據,然后將該數據回顯到客戶端。Socket 不指定任何消息協議,因此字符串“<EOF>”標記消息數據的結尾。它假定名為 listener
的 Socket 實例已初始化并綁定到終結點。
[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();
使用異步服務器套接字
異步服務器套接字使用 .NET 框架異步編程模型處理網絡服務請求。Socket 類遵循標準 .NET 異步命名模式;例如,同步 Accept 方法對應異步 BeginAccept 和 EndAccept 方法。
異步服務器套接字需要一個開始接受網絡連接請求的方法,一個處理連接請求并開始接收網絡數據的回調方法以及一個結束接收數據的回調方法。本節將進一步討論所有這些方法。
在下面的示例中,為開始接受網絡連接請求,方法 StartListening
初始化 Socket,然后使用 BeginAccept 方法開始接受新連接。當套接字上接收到新連接請求時調用接受回調方法。它負責獲取將處理連接的 Socket 實例,并將 Socket 提交給將處理請求的線程。接受回調方法實現 AsyncCallback 委托;它返回 void,并帶一個 IAsyncResult 類型的參數。下面的示例是接受回調方法的外殼程序。
[C#]
void acceptCallback( IAsyncResult ar) {
//Add the callback code here.
}
BeginAccept 方法帶兩個參數:指向接受回調方法的 AsyncCallback 委托和一個用于將狀態信息傳遞給回調方法的對象。在下面的示例中,偵聽 Socket 通過狀態參數傳遞給回調方法。本示例創建一個 AsyncCallback 委托并開始接受網絡連接。
[C#]
listener.BeginAccept(
new AsyncCallback(SocketListener.acceptCallback),
listener);
異步套接字使用系統線程池中的線程處理傳入的連接。一個線程負責接受連接,另一線程用于處理每個傳入的連接,還有一個線程負責接收連接數據。這些線程可以是同一個線程,具體取決于線程池所分配的線程。在下面的示例中,System.Threading.ManualResetEvent 類掛起主線程的執行并在執行可以繼續時發出信號。
下面的示例顯示在本地計算機上創建異步 TCP/IP 套接字并開始接受連接的異步方法。它假定以下內容:存在一個名為 allDone
的全局 ManualResetEvent 實例,該方法是名為 SocketListener
類的成員,以及定義了一個名為 acceptCallback
的回調方法。
[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(
new AsyncCallback(SocketListener.acceptCallback),
listener );
allDone.WaitOne();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine( "Closing the listener...");
}
接受回調方法(即前例中的 acceptCallback
)負責向主應用程序發出信號,讓它繼續執行處理、建立與客戶端的連接并開始異步讀取客戶端數據。下面的示例是 acceptCallback
方法實現的第一部分。該方法的此節向主應用程序線程發出信號,讓它繼續處理并建立與客戶端的連接。它假定存在一個名為 allDone
的全局 ManualResetEvent 實例。
[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.
}
從客戶端套接字讀取數據需要一個在異步調用之間傳遞值的狀態對象。下面的示例實現一個用于從遠程客戶端接收字符串的狀態對象。它包含以下各項的字段:客戶端套接字,用于接收數據的數據緩沖區,以及用于創建客戶端發送的數據字符串的 StringBuilder。將這些字段放在該狀態對象中,使這些字段的值在多個調用之間得以保留,以便從客戶端套接字讀取數據。
[C#]
public class StateObject {
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
開始從客戶端套接字接收數據的 acceptCallback
方法的此節首先初始化 StateObject
類的一個實例,然后調用 BeginReceive 方法以開始從客戶端套接字異步讀取數據。
下面的示例顯示了完整的 acceptCallback
方法。它假定以下內容:存在一個名為 allDone
的 ManualResetEvent 實例,定義了 StateObject
類,以及在名為 SocketListener
的類中定義了 readCallback
方法。
[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);
}
需要為異步套接字服務器實現的 final 方法是返回客戶端發送的數據的讀取回調方法。與接受回調方法一樣,讀取回調方法也是一個 AsyncCallback 委托。該方法將來自客戶端套接字的一個或多個字節讀入數據緩沖區,然后再次調用 BeginReceive 方法,直到客戶端發送的數據完成為止。從客戶端讀取整個消息后,在控制臺上顯示字符串,并關閉處理與客戶端的連接的服務器套接字。
下面的示例實現 readCallback
方法。它假定定義了 StateObject
類。
[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();
}
}
同步客戶端套接字示例
下面的示例程序創建一個連接到服務器的客戶端。該客戶端是用同步套接字生成的,因此掛起客戶端應用程序的執行,直到服務器返回響應為止。該應用程序將字符串發送到服務器,然后在控制臺顯示該服務器返回的字符串。
[C#]
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient {
public static void StartClient() {
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}
public static int Main(String[] args) {
StartClient();
return 0;
}
}