基于TCP异步Socket模型的介绍
发布时间:2022-08-05 23:43:25
标签:socket,异步
TCP异步Socket模型
C#的TCP异步Socket模型是通过Begin-End模式实现的。例如提供BeginConnect、BeginAccept、 BeginSend 和 BeginReceive等。
IAsyncResult BeginAccept(AsyncCallback callback, object state);
AsyncCallback回调在函数执行完毕后执行。state对象被用于在执行函数和回调函数间传输信息。
Socket socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8888);
socket.Bind(iep);
socket.Listen(5);
socket.BeginAccept (new AsyncCallback(CallbackAccept), socket);
private void CallbackAccept(IAsyncResult iar)
{
Socket server = (Socket)iar.AsyncState;
Socket client = server.EndAccept(iar);
}
则在Accept一个TcpClient,需要维护TcpClient列表。
private List<TcpClientState> clients;
异步TCP服务器完整实现
/// <summary>
/// 异步TCP服务器
/// </summary>
public class AsyncTcpServer : IDisposable
{
#region Fields
private TcpListener listener;
private List<TcpClientState> clients;
private bool disposed = false;
#endregion
#region Ctors
/// <summary>
/// 异步TCP服务器
/// </summary>
/// <param name="listenPort">监听的端口</param>
public AsyncTcpServer(int listenPort)
: this(IPAddress.Any, listenPort)
{
}
/// <summary>
/// 异步TCP服务器
/// </summary>
/// <param name="localEP">监听的终结点</param>
public AsyncTcpServer(IPEndPoint localEP)
: this(localEP.Address, localEP.Port)
{
}
/// <summary>
/// 异步TCP服务器
/// </summary>
/// <param name="localIPAddress">监听的IP地址</param>
/// <param name="listenPort">监听的端口</param>
public AsyncTcpServer(IPAddress localIPAddress, int listenPort)
{
Address = localIPAddress;
Port = listenPort;
this.Encoding = Encoding.Default;
clients = new List<TcpClientState>();
listener = new TcpListener(Address, Port);
listener.AllowNatTraversal(true);
}
#endregion
#region Properties
/// <summary>
/// 服务器是否正在运行
/// </summary>
public bool IsRunning { get; private set; }
/// <summary>
/// 监听的IP地址
/// </summary>
public IPAddress Address { get; private set; }
/// <summary>
/// 监听的端口
/// </summary>
public int Port { get; private set; }
/// <summary>
/// 通信使用的编码
/// </summary>
public Encoding Encoding { get; set; }
#endregion
#region Server
/// <summary>
/// 启动服务器
/// </summary>
/// <returns>异步TCP服务器</returns>
public AsyncTcpServer Start()
{
if (!IsRunning)
{
IsRunning = true;
listener.Start();
listener.BeginAcceptTcpClient(
new AsyncCallback(HandleTcpClientAccepted), listener);
}
return this;
}
/// <summary>
/// 启动服务器
/// </summary>
/// <param name="backlog">
/// 服务器所允许的挂起连接序列的最大长度
/// </param>
/// <returns>异步TCP服务器</returns>
public AsyncTcpServer Start(int backlog)
{
if (!IsRunning)
{
IsRunning = true;
listener.Start(backlog);
listener.BeginAcceptTcpClient(
new AsyncCallback(HandleTcpClientAccepted), listener);
}
return this;
}
/// <summary>
/// 停止服务器
/// </summary>
/// <returns>异步TCP服务器</returns>
public AsyncTcpServer Stop()
{
if (IsRunning)
{
IsRunning = false;
listener.Stop();
lock (this.clients)
{
for (int i = 0; i < this.clients.Count; i++)
{
this.clients[i].TcpClient.Client.Disconnect(false);
}
this.clients.Clear();
}
}
return this;
}
#endregion
#region Receive
private void HandleTcpClientAccepted(IAsyncResult ar)
{
if (IsRunning)
{
TcpListener tcpListener = (TcpListener)ar.AsyncState;
TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar);
byte[] buffer = new byte[tcpClient.ReceiveBufferSize];
TcpClientState internalClient
= new TcpClientState(tcpClient, buffer);
lock (this.clients)
{
this.clients.Add(internalClient);
RaiseClientConnected(tcpClient);
}
NetworkStream networkStream = internalClient.NetworkStream;
networkStream.BeginRead(
internalClient.Buffer,
0,
internalClient.Buffer.Length,
HandleDatagramReceived,
internalClient);
tcpListener.BeginAcceptTcpClient(
new AsyncCallback(HandleTcpClientAccepted), ar.AsyncState);
}
}
private void HandleDatagramReceived(IAsyncResult ar)
{
if (IsRunning)
{
TcpClientState internalClient = (TcpClientState)ar.AsyncState;
NetworkStream networkStream = internalClient.NetworkStream;
int numberOfReadBytes = 0;
try
{
numberOfReadBytes = networkStream.EndRead(ar);
}
catch
{
numberOfReadBytes = 0;
}
if (numberOfReadBytes == 0)
{
// connection has been closed
lock (this.clients)
{
this.clients.Remove(internalClient);
RaiseClientDisconnected(internalClient.TcpClient);
return;
}
}
// received byte and trigger event notification
byte[] receivedBytes = new byte[numberOfReadBytes];
Buffer.BlockCopy(
internalClient.Buffer, 0,
receivedBytes, 0, numberOfReadBytes);
RaiseDatagramReceived(internalClient.TcpClient, receivedBytes);
RaisePlaintextReceived(internalClient.TcpClient, receivedBytes);
// continue listening for tcp datagram packets
networkStream.BeginRead(
internalClient.Buffer,
0,
internalClient.Buffer.Length,
HandleDatagramReceived,
internalClient);
}
}
#endregion
#region Events
/// <summary>
/// 接收到数据报文事件
/// </summary>
public event EventHandler<TcpDatagramReceivedEventArgs<byte[]>> DatagramReceived;
/// <summary>
/// 接收到数据报文明文事件
/// </summary>
public event EventHandler<TcpDatagramReceivedEventArgs<string>> PlaintextReceived;
private void RaiseDatagramReceived(TcpClient sender, byte[] datagram)
{
if (DatagramReceived != null)
{
DatagramReceived(this, new TcpDatagramReceivedEventArgs<byte[]>(sender, datagram));
}
}
private void RaisePlaintextReceived(TcpClient sender, byte[] datagram)
{
if (PlaintextReceived != null)
{
PlaintextReceived(this, new TcpDatagramReceivedEventArgs<string>(
sender, this.Encoding.GetString(datagram, 0, datagram.Length)));
}
}
/// <summary>
/// 与客户端的连接已建立事件
/// </summary>
public event EventHandler<TcpClientConnectedEventArgs> ClientConnected;
/// <summary>
/// 与客户端的连接已断开事件
/// </summary>
public event EventHandler<TcpClientDisconnectedEventArgs> ClientDisconnected;
private void RaiseClientConnected(TcpClient tcpClient)
{
if (ClientConnected != null)
{
ClientConnected(this, new TcpClientConnectedEventArgs(tcpClient));
}
}
private void RaiseClientDisconnected(TcpClient tcpClient)
{
if (ClientDisconnected != null)
{
ClientDisconnected(this, new TcpClientDisconnectedEventArgs(tcpClient));
}
}
#endregion
#region Send
/// <summary>
/// 发送报文至指定的客户端
/// </summary>
/// <param name="tcpClient">客户端</param>
/// <param name="datagram">报文</param>
public void Send(TcpClient tcpClient, byte[] datagram)
{
if (!IsRunning)
throw new InvalidProgramException("This TCP server has not been started.");
if (tcpClient == null)
throw new ArgumentNullException("tcpClient");
if (datagram == null)
throw new ArgumentNullException("datagram");
tcpClient.GetStream().BeginWrite(
datagram, 0, datagram.Length, HandleDatagramWritten, tcpClient);
}
private void HandleDatagramWritten(IAsyncResult ar)
{
((TcpClient)ar.AsyncState).GetStream().EndWrite(ar);
}
/// <summary>
/// 发送报文至指定的客户端
/// </summary>
/// <param name="tcpClient">客户端</param>
/// <param name="datagram">报文</param>
public void Send(TcpClient tcpClient, string datagram)
{
Send(tcpClient, this.Encoding.GetBytes(datagram));
}
/// <summary>
/// 发送报文至所有客户端
/// </summary>
/// <param name="datagram">报文</param>
public void SendAll(byte[] datagram)
{
if (!IsRunning)
throw new InvalidProgramException("This TCP server has not been started.");
for (int i = 0; i < this.clients.Count; i++)
{
Send(this.clients[i].TcpClient, datagram);
}
}
/// <summary>
/// 发送报文至所有客户端
/// </summary>
/// <param name="datagram">报文</param>
public void SendAll(string datagram)
{
if (!IsRunning)
throw new InvalidProgramException("This TCP server has not been started.");
SendAll(this.Encoding.GetBytes(datagram));
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing,
/// releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release
/// both managed and unmanaged resources; <c>false</c>
/// to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
try
{
Stop();
if (listener != null)
{
listener = null;
}
}
catch (SocketException ex)
{
ExceptionHandler.Handle(ex);
}
}
disposed = true;
}
}
#endregion
}
使用举例
class Program
{
static AsyncTcpServer server;
static void Main(string[] args)
{
LogFactory.Assign(new ConsoleLogFactory());
server = new AsyncTcpServer(9999);
server.Encoding = Encoding.UTF8;
server.ClientConnected +=
new EventHandler<TcpClientConnectedEventArgs>(server_ClientConnected);
server.ClientDisconnected +=
new EventHandler<TcpClientDisconnectedEventArgs>(server_ClientDisconnected);
server.PlaintextReceived +=
new EventHandler<TcpDatagramReceivedEventArgs<string>>(server_PlaintextReceived);
server.Start();
Console.WriteLine("TCP server has been started.");
Console.WriteLine("Type something to send to client...");
while (true)
{
string text = Console.ReadLine();
server.SendAll(text);
}
}
static void server_ClientConnected(object sender, TcpClientConnectedEventArgs e)
{
Logger.Debug(string.Format(CultureInfo.InvariantCulture,
"TCP client {0} has connected.",
e.TcpClient.Client.RemoteEndPoint.ToString()));
}
static void server_ClientDisconnected(object sender, TcpClientDisconnectedEventArgs e)
{
Logger.Debug(string.Format(CultureInfo.InvariantCulture,
"TCP client {0} has disconnected.",
e.TcpClient.Client.RemoteEndPoint.ToString()));
}
static void server_PlaintextReceived(object sender, TcpDatagramReceivedEventArgs<string> e)
{
if (e.Datagram != "Received")
{
Console.Write(string.Format("Client : {0} --> ",
e.TcpClient.Client.RemoteEndPoint.ToString()));
Console.WriteLine(string.Format("{0}", e.Datagram));
server.Send(e.TcpClient, "Server has received you text : " + e.Datagram);
}
}
}


猜你喜欢
- 1.字节码增强技术字节码增强技术就是一类对现有字节码进行修改或者动态生成全新字节码文件的技术。参考地址2.常见技术技术分类类型静态增强Asp
- HttpClient模拟浏览器登录后发起请求浏览器实现这个效果需要如下几个步骤: 1请求一个需要登录的页
- 一、异步模型的基本概述异步编程的核心是 Task 和 Task<T> 对象,这两个对象对异步操作建模。 它们受关键字 async
- 目录什么是Insets?Insets相关类InsetsStateInsetsStateControllerInsetsSourceInset
- 前言安卓的Material库提供了许多样式更精美的控件,其中就有悬浮控件,它表现出一种悬浮在页面的效果,也就是有立体效果的,让人产生这种控件
- 一:.Net中有两个类 HttpWebRequest 和HttpWebResponse 类来实现Http的请求实现步骤:1.通过WebReq
- 在Android中使用SQLite数据库的入门指南,打算分下面几部分与大家一起分享, 1、什么是SQLite 2、Android中使用SQL
- C语言奇偶排序算法奇偶排序,或奇偶换位排序,或砖排序,是一种相对简单的排序算法,最初发明用于有本地互连的并行计算。这是与冒泡排序特点类似的一
- Java未被捕获的异常在你学习在程序中处理异常之前,看一看如果你不处理它们会有什么情况发生是很有好处的。下面的小程序包括一个故意导致被零除错
- 序、前言emmmmm,首先这篇文章讲的不是用BinaryFormatter来进行结构体的二进制转换,说真的BinaryFormatter这个
- 前言本文主要介绍了关于android实现一键锁屏和一键卸载的相关内容,分享出来供大家参考学习,这两个功能也是大家在开发中会遇到的两个需求,下
- 本文实例讲述了退出Android程序时清除所有activity的方法。分享给大家供大家参考,具体如下:在一个项目中,要退出android程序
- 一、简介现在的Android应用程序中,不可避免的都会使用到图片,如果每次加载图片的时候都要从网络重新拉取,这样不但很耗费用户的流量,而且图
- 摘要:用spring-boot开发RESTful API非常的方便,在生产环境中,对发布的API增加授权保护是非常必要的。现在我们来看如何利
- 目录一、C# 多态性二、静态多态性三、函数重载四、C# 运算符重载1、运算符重载的实现2、可重载和不可重载运算符五、动态多态性前言:👻🎄学过
- 文件上传的方法主要目前有两个常用的,一个是SmartUpload,一个是Apache的Commons fileupload.我们这里主要介绍
- 目录I. 环境配置1. 项目配置2. 数据库表II. 传参类型确定1. 参数类型为整形2. 指定jdbcType3. 传参类型为String
- 前言相信很多Java开发都遇到过一个面试题:Resource和Autowired的区别是什么?这个问题的答案相信基本都清楚,但是这两者在Sp
- 一、Json简介Json(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JS的一个子集。 Jso
- 概述状态模式允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。这个模式将状态封装成独立的类,并将动作委托到 代表当前状态的对