在C#中,使用Socket進行異步通信可以提高程序的性能和響應能力
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class AsyncSocketServer
{
private Socket _serverSocket;
private const int BufferSize = 1024;
public void StartListening(int port)
{
// 創建一個TCP/IP套接字
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 綁定到本地端口
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
_serverSocket.Bind(localEndPoint);
// 開始監聽客戶端連接
_serverSocket.Listen(100);
Console.WriteLine($"服務器正在監聽端口 {port}...");
// 等待客戶端連接
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), _serverSocket);
}
private void AcceptCallback(IAsyncResult ar)
{
// 獲取服務器套接字
Socket serverSocket = (Socket)ar.AsyncState;
// 接受客戶端連接
Socket clientSocket = serverSocket.EndAccept(ar);
// 打印客戶端信息
Console.WriteLine($"客戶端 {clientSocket.RemoteEndPoint} 已連接");
// 準備接收數據的緩沖區
byte[] buffer = new byte[BufferSize];
// 開始異步接收數據
clientSocket.BeginReceive(buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
// 繼續等待其他客戶端連接
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket);
}
private void ReceiveCallback(IAsyncResult ar)
{
// 獲取客戶端套接字
Socket clientSocket = (Socket)ar.AsyncState;
try
{
// 結束異步接收操作
int bytesRead = clientSocket.EndReceive(ar);
if (bytesRead > 0)
{
// 解碼接收到的數據
string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
// 打印接收到的數據
Console.WriteLine($"從客戶端 {clientSocket.RemoteEndPoint} 接收到數據: {receivedData}");
// 準備發送的數據
byte[] sendBuffer = Encoding.ASCII.GetBytes("你好,我是服務器!");
// 開始異步發送數據
clientSocket.BeginSend(sendBuffer, 0, sendBuffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), clientSocket);
}
}
catch (Exception ex)
{
Console.WriteLine($"接收數據時出錯: {ex.Message}");
clientSocket.Close();
}
}
private void SendCallback(IAsyncResult ar)
{
// 獲取客戶端套接字
Socket clientSocket = (Socket)ar.AsyncState;
try
{
// 結束異步發送操作
int bytesSent = clientSocket.EndSend(ar);
// 打印發送的數據長度
Console.WriteLine($"向客戶端 {clientSocket.RemoteEndPoint} 發送了 {bytesSent} 字節的數據");
// 準備接收下一批數據的緩沖區
byte[] buffer = new byte[BufferSize];
// 開始異步接收數據
clientSocket.BeginReceive(buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
}
catch (Exception ex)
{
Console.WriteLine($"發送數據時出錯: {ex.Message}");
clientSocket.Close();
}
}
}
AsyncSocketServer
類:class Program
{
static void Main(string[] args)
{
AsyncSocketServer server = new AsyncSocketServer();
server.StartListening(8080);
Console.WriteLine("按任意鍵退出...");
Console.ReadKey();
}
}
這個示例展示了如何使用C# Socket進行異步通信。當客戶端連接到服務器時,服務器會異步接收客戶端發送的數據,并將數據原樣發送回客戶端。你可以根據需要修改此示例以實現更復雜的通信功能。