這篇文章將為大家詳細講解有關(guān)C#中怎么利用Socket實現(xiàn)異步通訊,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
創(chuàng)新互聯(lián)從2013年開始,公司以成都做網(wǎng)站、網(wǎng)站建設(shè)、系統(tǒng)開發(fā)、網(wǎng)絡(luò)推廣、文化傳媒、企業(yè)宣傳、平面廣告設(shè)計等為主要業(yè)務(wù),適用行業(yè)近百種。服務(wù)企業(yè)客戶近千家,涉及國內(nèi)多個省份客戶。擁有多年網(wǎng)站建設(shè)開發(fā)經(jīng)驗。為企業(yè)提供專業(yè)的網(wǎng)站建設(shè)、創(chuàng)意設(shè)計、宣傳推廣等服務(wù)。 通過專業(yè)的設(shè)計、獨特的風格,為不同客戶提供各種風格的特色服務(wù)。
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);
// 與目標終端連接.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
//等待,直到連接程序完成。在ConnectCallback中適當位置有connecDone.Set()語句
connectDone.WaitOne();
// 發(fā)送數(shù)據(jù)到遠程終端.
Send(client, "This is a test<EOF>");
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異步通訊客戶端之數(shù)據(jù)接收:
private static void Receive(Socket client)
try {{
// 構(gòu)造容器state.
StateObject state = new StateObject();
state.workSocket = client;
// 從遠程目標接收數(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;
}
}
關(guān)于C#中怎么利用Socket實現(xiàn)異步通訊就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
網(wǎng)頁題目:C#中怎么利用Socket實現(xiàn)異步通訊
本文鏈接:http://aaarwkj.com/article44/pccpee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供、網(wǎng)站收錄、網(wǎng)站改版、面包屑導航、域名注冊、小程序開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)