在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进行异步通信。当客户端连接到服务器时,服务器会异步接收客户端发送的数据,并将数据原样发送回客户端。你可以根据需要修改此示例以实现更复杂的通信功能。