詳解C# Socket異步通訊實例。本站提示廣大學習愛好者:(詳解C# Socket異步通訊實例)文章只能為提供參考,不一定能成為您想要的結果。以下是詳解C# Socket異步通訊實例正文
TCPServer
1、運用的通訊通道:socket
2、用到的根本功用:
①Bind,
②Listen,
③BeginAccept
④EndAccept
⑤BeginReceive
⑥EndReceive
3、函數參數闡明
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
新建socket所運用的參數均為零碎預定義的量,直接選取運用。
listener.Bind(localEndPoint);
localEndPoint 表示一個定義完好的終端,包括IP和端口信息。
//new IPEndPoint(IPAddress,port) //IPAdress.Parse("192.168.1.3") listener.Listen(100);
監聽
listener.BeginAccept( new AsyncCallback(AcceptCallback), listener);
AsyncCallback(AcceptCallback),一旦銜接上後的回調函數為AcceptCallback。當零碎調用這個函數時,自動賦予的輸出參數為IAsyncResoult類型變量ar。
listener,銜接行為的容器。
Socket handler = listener.EndAccept(ar);
完成銜接,前往此時的socket通道。
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
接納的字節,0,字節長度,0,接納時調用的回調函數,接納行為的容器。
========
容器的構造類型為:
public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); }
容器至多為一個socket類型。
===============
// Read data from the client socket. int bytesRead = handler.EndReceive(ar);
完成一次銜接。數據存儲在state.buffer裡,bytesRead為讀取的長度。
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
發送數據byteData,回調函數SendCallback。容器handler
int bytesSent = handler.EndSend(ar);
發送終了,bytesSent發送字節數。
4 順序構造
主順序:
byte[] bytes = new Byte[1024]; IPAddress ipAddress = IPAddress.Parse("192.168.1.104"); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); // 生成一個TCP的socket Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.Bind(localEndPoint); listener.Listen(100); while (true) { // Set the event to nonsignaled state. allDone.Reset(); //開啟異步監聽socket Console.WriteLine("Waiting for a connection"); listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); // 讓順序等候,直到銜接義務完成。在AcceptCallback裡的適當地位放置allDone.Set()語句. allDone.WaitOne(); } Console.WriteLine("\nPress ENTER to continue"); Console.Read();
銜接行為回調函數AcceptCallback:
public static void AcceptCallback(IAsyncResult ar) { //添加此命令,讓主線程持續. allDone.Set(); // 獲取客戶懇求的socket Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // 造一個容器,並用於接納命令. StateObject state = new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); }
讀取行為的回調函數ReadCallback:
public static void ReadCallback(IAsyncResult ar) { String content = String.Empty; // 從異步state對象中獲取state和socket對象. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; // 從客戶socket讀取數據. int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { // 假如接納到數據,則存起來 state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)); // 反省能否有完畢標志,假如沒有則持續讀取 content = state.sb.ToString(); if (content.IndexOf("<EOF>") > -1) { //一切數據讀取終了. Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content); // 給客戶端呼應. Send(handler, content); } else { // 接納未完成,持續接納. handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } } }
發送音訊給客戶端:
private static void Send(Socket handler, String data) { // 音訊格式轉換. byte[] byteData = Encoding.ASCII.GetBytes(data); // 開端發送數據給近程目的. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } private static void SendCallback(IAsyncResult ar) { // 從state對象獲取socket. Socket handler = (Socket)ar.AsyncState; //完成數據發送 int bytesSent = handler.EndSend(ar); Console.WriteLine("Sent {0} bytes to client.", bytesSent); handler.Shutdown(SocketShutdown.Both); handler.Close(); }
在各種行為的回調函數中,所對應的socket都從輸出參數的AsyncState屬性取得。運用(Socket)或許(StateObject)停止強迫轉換。BeginReceive函數運用的容器為state,由於它需求寄存傳送的數據。
而其他接納或發送函數的容器為socket也可。
完好代碼
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; // State object for reading client data asynchronously public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = ; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } public class AsynchronousSocketListener { // Thread signal. public static ManualResetEvent allDone = new ManualResetEvent(false); public AsynchronousSocketListener() { } public static void StartListening() { // Data buffer for incoming data. byte[] bytes = new Byte[]; // Establish the local endpoint for the socket. // The DNS name of the computer // running the listener is "host.contoso.com". //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = IPAddress.Parse("..."); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, ); // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(); while (true) { // Set the event to nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. Console.WriteLine("Waiting for a connection"); listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); // Wait until a connection is made before continuing. allDone.WaitOne(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue"); Console.Read(); } public static void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. allDone.Set(); // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. StateObject state = new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, , StateObject.BufferSize, , new AsyncCallback(ReadCallback), state); } public static void ReadCallback(IAsyncResult ar) { String content = String.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); if (bytesRead > ) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString( state.buffer, , bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = state.sb.ToString(); if (content.IndexOf("<EOF>") > -) { // All the data has been read from the // client. Display it on the console. Console.WriteLine("Read {} bytes from socket. \n Data : {}",content.Length, content); // Echo the data back to the client. Send(handler, content); } else { // Not all data received. Get more. handler.BeginReceive(state.buffer, , StateObject.BufferSize, , new AsyncCallback(ReadCallback), state); } } } private static void Send(Socket handler, 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. handler.BeginSend(byteData, , byteData.Length, , new AsyncCallback(SendCallback), handler); } private static void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket handler = (Socket)ar.AsyncState; // Complete sending the data to the remote device. int bytesSent = handler.EndSend(ar); Console.WriteLine("Sent {} bytes to client.", bytesSent); handler.Shutdown(SocketShutdown.Both); handler.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } public static int Main(String[] args) { StartListening(); return ; } }
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。