新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C#Socket異步通訊實現(xiàn)詳解
C# Socket異步通訊客戶端實現(xiàn)源碼

達拉特網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站等網(wǎng)站項目制作,到程序開發(fā),運營維護。創(chuàng)新互聯(lián)公司于2013年創(chuàng)立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。
C# Socket異步通訊客戶端之主程序:
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.Text;
- // State object for receiving data from remote device.
- 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];
- // Received data string.
- public StringBuilder sb = new StringBuilder();
- }
- public class AsynchronousClient {
- // The port number for the remote device.
- private const int port = 11000;
- // ManualResetEvent instances signal completion.
- private static ManualResetEvent connectDone =
- new ManualResetEvent(false);
- private static ManualResetEvent sendDone =
- new ManualResetEvent(false);
- private static ManualResetEvent receiveDone =
- new ManualResetEvent(false);
- // The response from the remote device.
- private static String response = String.Empty;
- private static void StartClient() {
// 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, port);- // 生成一個TCP/IP socket.
- Socket client = new Socket(AddressFamily.InterNetwork,
- SocketType.Stream, ProtocolType.Tcp);
- // 與目標(biāo)終端連接.
- client.BeginConnect(remoteEP,
- new AsyncCallback(ConnectCallback), client);
- //等待,直到連接程序完成。在ConnectCallback中適當(dāng)位置有connecDone.Set()語句
- connectDone.WaitOne();
- // 發(fā)送數(shù)據(jù)到遠程終端.
- Send(client, "This is a test
"); - sendDone.WaitOne();
- // 接收返回數(shù)據(jù).
- Receive(client);
- receiveDone.WaitOne();
- // Write the response to the console.
- Console.WriteLine("Response received : {0}", response);
- // Release the socket.
- client.Shutdown(SocketShutdown.Both);
- client.Close();
- return 0;
- }
C# Socket異步通訊客戶端之連接部分Callback:
- private static void ConnectCallback(IAsyncResult ar)
- {
- // 從state對象獲取socket.
- Socket client = (Socket)ar.AsyncState;
- // 完成連接.
- client.EndConnect(ar);
- Console.WriteLine("Socket connected to {0}",
- client.RemoteEndPoint.ToString());
- // 連接已完成,主線程繼續(xù).
- connectDone.Set();
- } catch (Exception e) {
- Console.WriteLine(e.ToString());
- }
- }
C# Socket異步通訊客戶端之?dāng)?shù)據(jù)接收:
- private static void Receive(Socket client)
- try {{
- // 構(gòu)造容器state.
- StateObject state = new StateObject();
- state.workSocket = client;
- // 從遠程目標(biāo)接收數(shù)據(jù).
- client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReceiveCallback), state);
- } catch (Exception e) {
- Console.WriteLine(e.ToString());
- }
}- private static void ReceiveCallback(IAsyncResult ar)
- {
- // 從輸入?yún)?shù)異步state對象中獲取state和socket對象
- StateObject state = (StateObject)ar.AsyncState;
- Socket client = state.workSocket;
- //從遠程設(shè)備讀取數(shù)據(jù)
- int bytesRead = client.EndReceive(ar);
- if (bytesRead > 0)
- {
- // 有數(shù)據(jù),存儲.
- state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
- // 繼續(xù)讀取.
- client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReceiveCallback), state);
- }
- else
- {
- // 所有數(shù)據(jù)讀取完畢.
- if (state.sb.Length > 1)
- {
- response = state.sb.ToString();
- }
- // 所有數(shù)據(jù)讀取完畢的指示信號.
- receiveDone.Set();
- }
- } catch (Exception e) {
- Console.WriteLine(e.ToString());
- }
- }
C# Socket異步通訊客戶端之發(fā)送數(shù)據(jù):
- private static void Send(Socket client, String data)
- {
- // 格式轉(zhuǎn)換.
- byte[] byteData = Encoding.ASCII.GetBytes(data);
- // 開始發(fā)送數(shù)據(jù)到遠程設(shè)備.
- client.BeginSend(byteData, 0, byteData.Length, 0,
- new AsyncCallback(SendCallback), client);
- }
- private static void SendCallback(IAsyncResult ar)
- {
- // 從state對象中獲取socket
- Socket client = (Socket)ar.AsyncState;
- // 完成數(shù)據(jù)發(fā)送.
- int bytesSent = client.EndSend(ar);
- Console.WriteLine("Sent {0} bytes to server.", bytesSent);
- // 指示數(shù)據(jù)已經(jīng)發(fā)送完成,主線程繼續(xù).
- sendDone.Set();
- }
- } catch (Exception e) {
- Console.WriteLine(e.ToString());
- }
- }
- public static int Main(String[] args) {
- StartClient();
- return 0;
- }
- }
C# Socket異步通訊客戶端的實現(xiàn)源碼內(nèi)容就基本向你介紹到這里,希望對你了解和學(xué)習(xí)C# Socket異步通訊有所幫助。
分享文章:C#Socket異步通訊實現(xiàn)詳解
文章地址:http://m.fisionsoft.com.cn/article/ccseohd.html


咨詢
建站咨詢
