下面我将为您详细讲解“.NET的Socket异步通讯示例分享”的攻略。
一、什么是Socket异步通讯
在计算机网络中,Socket(套接字)是指一个可以收发信息的网络通信端点,常用于客户端与服务器之间的通信。异步通讯是指通讯双方在任何时候都可以独立地发送和接收消息,不需要等待对方的响应。
在.NET中,可以使用Socket类实现Socket异步通讯,它提供了一组异步操作方法,使程序可以实现非阻塞式的通讯,从而提高程序的效率和可靠性。
二、Socket异步通讯的示例
1. 服务器端异步通讯示例
下面是一个简单的服务器端异步通讯示例,它使用了Socket类的BeginAccept方法异步等待客户端的连接请求,并在连接成功后使用BeginReceive方法异步接收客户端发送的数据:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static readonly Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static void Main(string[] args)
{
listenSocket.Bind(new IPEndPoint(IPAddress.Any, 8888));
listenSocket.Listen(100);
Console.WriteLine("Server started, waiting for clients...");
Accept();
Console.ReadLine();
}
static void Accept()
{
listenSocket.BeginAccept(ar =>
{
var client = listenSocket.EndAccept(ar);
Console.WriteLine($"Client connected: {client.RemoteEndPoint}");
var buffer = new byte[1024];
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receive, client);
Accept();
}, null);
}
static void Receive(IAsyncResult ar)
{
var client = (Socket)ar.AsyncState;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Message received from {client.RemoteEndPoint}: {message}");
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receive, client);
}
else
{
Console.WriteLine($"Client disconnected: {client.RemoteEndPoint}");
client.Close();
}
}
}
2. 客户端异步通讯示例
下面是一个简单的客户端异步通讯示例,它使用了Socket类的BeginConnect方法异步连接服务器,并在连接成功后使用BeginSend方法异步发送数据:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main(string[] args)
{
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888), ar =>
{
client.EndConnect(ar);
Console.WriteLine($"Connected to server: {client.RemoteEndPoint}");
var message = Encoding.UTF8.GetBytes("Hello from client");
client.BeginSend(message, 0, message.Length, SocketFlags.None, Send, client);
}, null);
Console.ReadLine();
}
static void Send(IAsyncResult ar)
{
var client = (Socket)ar.AsyncState;
client.EndSend(ar);
Console.WriteLine("Message sent to server");
var buffer = new byte[1024];
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receive, client);
}
static void Receive(IAsyncResult ar)
{
var client = (Socket)ar.AsyncState;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Message received from server: {message}");
}
else
{
Console.WriteLine("Server disconnected");
client.Close();
}
}
}
以上就是两个简单的Socket异步通讯示例,它们实现了非阻塞式的通讯,能够提高程序的效率和可靠性。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:.net的socket异步通讯示例分享 - Python技术站