C# 高效Socket运行机制系列文章一 SocketAsyncEventArgs

        微软创建了SocketAsyncEventArgs类来帮助你编写可扩展、高性能socket服务器代码。

        SocketAsyncEventArgs使用网络套接字类System.Net通过异步方法完成I / O端口通讯。在以下的文章中我们会实现一个基于windows TCP/IP协议的可靠的,可扩展的Socket通讯。Microsoft 对相关技术的说明可以参考SocketAsyncEventArgs I/O Completion Ports

        SocketAsyncEventArgs帮助我们访问一个套接字,它有异步工作的优点,可以设置缓冲区空间、对象池,同时响应完成事件Completed event。有一个状态对象,可以通过属性访问套接字。

        这篇文章的目的是帮助你理解的基本使用SocketAsyncEventArgs类。

        对于SocketAsyncEventArgs类,微软的网站说,它需要“平台:Windows 7,Windows Vista、Windows XP SP3、Windows Server 2008、Windows Server 2003。NET Framework Client Profile框架支持:4、3.5 SP1,3.0 SP1,2.0 SP1。()。NET Framework Client Profile框架客户概要支持:4、3.5 SP1。”


 NameDescription
Public propertyAcceptSocketGets or sets the socket to use or the socket created for accepting a connection with an asynchronous socket method.
Public propertyBufferGets the data buffer to use with an asynchronous socket method.
Public propertyBufferListGets or sets an array of data buffers to use with an asynchronous socket method.
Public propertyBytesTransferredGets the number of bytes transferred in the socket operation.
Public propertyConnectByNameErrorGets the exception in the case of a connection failure when a DnsEndPoint was used.
Public propertyConnectSocketThe created and connected Socket object after successful completion of the ConnectAsync method.
Public propertyCountGets the maximum amount of data, in bytes, to send or receive in an asynchronous operation.
Public propertyDisconnectReuseSocketGets or sets a value that specifies if socket can be reused after a disconnect operation.
Public propertyLastOperationGets the type of socket operation most recently performed with this context object.
Public propertyOffsetGets the offset, in bytes, into the data buffer referenced by the Buffer property.
Public propertyReceiveMessageFromPacketInfoGets the IP address and interface of a received packet.
Public propertyRemoteEndPointGets or sets the remote IP endpoint for an asynchronous operation.
Public propertySendPacketsElementsGets or sets an array of buffers to be sent for an asynchronous operation used by the Socket.SendPacketsAsync method.
Public propertySendPacketsFlagsGets or sets a bitwise combination of TransmitFileOptions values for an asynchronous operation used by the Socket.SendPacketsAsync method.
Public propertySendPacketsSendSizeGets or sets the size, in bytes, of the data block used in the send operation.
Public propertySocketClientAccessPolicyProtocolObsolete. Gets or sets the protocol to use to download the socket client access policy file.
Public propertySocketErrorGets or sets the result of the asynchronous socket operation.
Public propertySocketFlagsGets the results of an asynchronous socket operation or sets the behavior of an asynchronous operation.
Public propertyUserTokenGets or sets a user or application object associated with this asynchronous socket operation.

 NameDescription
Public methodDisposeReleases the unmanaged resources used by the SocketAsyncEventArgs instance and optionally disposes of the managed resources.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeFrees resources used by the SocketAsyncEventArgs class. (Overrides Object.Finalize().)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodOnCompletedRepresents a method that is called when an asynchronous operation completes.
Public methodSetBuffer(Int32, Int32)Sets the data buffer to use with an asynchronous socket method.
Public methodSetBuffer(Byte[], Int32, Int32)Sets the data buffer to use with an asynchronous socket method.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)

 NameDescription
Public eventCompletedThe event used to complete an asynchronous operation.

下一扁文章我会针对TCP协议进行进一步的说明


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
探索全栈前端技术的魅力:HTML+CSS+JS+JQ+Bootstrap网站源码深度解析 在这个数字化时代,构建一个既美观又功能强大的网站成为了许多开发者和企业追逐的目标。本份资源精心汇集了一套完整网站源码,融合了HTML的骨架搭建、CSS的视觉美化、JavaScript的交互逻辑、jQuery的高效操作以及Bootstrap的响应式设计,全方位揭秘了现代网页开发的精髓。 HTML,作为网页的基础,它构建了信息的框架;CSS则赋予网页生动的外观,让设计创意跃然屏上;JavaScript的加入,使网站拥有了灵动的交互体验;jQuery,作为JavaScript的强力辅助,简化了DOM操作与事件处理,让编码更为高效;而Bootstrap的融入,则确保了网站在不同设备上的完美呈现,响应式设计让访问无界限。 通过这份源码,你将: 学习如何高效组织HTML结构,提升页面加载速度与SEO友好度; 掌握CSS高级技巧,如Flexbox与Grid布局,打造适应各种屏幕的视觉盛宴; 理解JavaScript核心概念,动手实现动画、表单验证等动态效果; 利用jQuery插件快速增强用户体验,实现滑动效果、Ajax请求等; 深入Bootstrap框架,掌握移动优先的开发策略,响应式设计信手拈来。 无论是前端开发新手渴望系统学习,还是资深开发者寻求灵感与实用技巧,这份资源都是不可多得的宝藏。立即深入了解,开启你的全栈前端探索之旅,让每一个网页都成为技术与艺术的完美融合!
好的,下面是一个简单的C# Socket服务端使用SocketAsyncEventArgs的示例代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Threading; public class SocketServer { private Socket m_serverSocket; private Semaphore m_maxAcceptedClients; private SocketAsyncEventArgsPool m_readWritePool; public SocketServer(int maxConnections) { m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 1234)); m_serverSocket.Listen(maxConnections); m_maxAcceptedClients = new Semaphore(maxConnections, maxConnections); m_readWritePool = new SocketAsyncEventArgsPool(maxConnections); for (int i = 0; i < maxConnections; i++) { SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs(); readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed); readEventArgs.UserToken = new AsyncUserToken(); m_readWritePool.Push(readEventArgs); } } public void Start() { StartAccept(null); } private void StartAccept(SocketAsyncEventArgs acceptEventArgs) { if (acceptEventArgs == null) { acceptEventArgs = new SocketAsyncEventArgs(); acceptEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed); } else { acceptEventArgs.AcceptSocket = null; } m_maxAcceptedClients.WaitOne(); if (!m_serverSocket.AcceptAsync(acceptEventArgs)) { ProcessAccept(acceptEventArgs); } } private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { SocketAsyncEventArgs readEventArgs = m_readWritePool.Pop(); AsyncUserToken userToken = (AsyncUserToken)readEventArgs.UserToken; userToken.Socket = acceptEventArgs.AcceptSocket; userToken.ReadEventArgs = readEventArgs; readEventArgs.AcceptSocket = userToken.Socket; if (!userToken.Socket.ReceiveAsync(readEventArgs)) { ProcessReceive(readEventArgs); } StartAccept(acceptEventArgs); } private void Accept_Completed(object sender, SocketAsyncEventArgs e) { ProcessAccept(e); } private void IO_Completed(object sender, SocketAsyncEventArgs e) { switch (e.LastOperation) { case SocketAsyncOperation.Receive: ProcessReceive(e); break; case SocketAsyncOperation.Send: ProcessSend(e); break; default: throw new ArgumentException("The last operation completed on the socket was not a receive or send"); } } private void ProcessReceive(SocketAsyncEventArgs e) { AsyncUserToken userToken = (AsyncUserToken)e.UserToken; if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { userToken.Data.AddRange(e.Buffer.Take(e.BytesTransferred)); if (userToken.Data.Count >= 4) { int len = BitConverter.ToInt32(userToken.Data.Take(4).ToArray(), 0); if (userToken.Data.Count >= 4 + len) { byte[] buffer = userToken.Data.Skip(4).Take(len).ToArray(); userToken.Data.RemoveRange(0, 4 + len); // 处理请求并响应 byte[] response = HandleRequest(buffer); Send(userToken.Socket, response); return; } } if (!userToken.Socket.ReceiveAsync(e)) { ProcessReceive(e); } } else { CloseClientSocket(userToken); } } private void ProcessSend(SocketAsyncEventArgs e) { AsyncUserToken userToken = (AsyncUserToken)e.UserToken; if (e.SocketError == SocketError.Success) { if (!userToken.Socket.ReceiveAsync(userToken.ReadEventArgs)) { ProcessReceive(userToken.ReadEventArgs); } } else { CloseClientSocket(userToken); } } private void Send(Socket socket, byte[] buffer) { SocketAsyncEventArgs sendEventArgs = new SocketAsyncEventArgs(); sendEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed); sendEventArgs.SetBuffer(buffer, 0, buffer.Length); sendEventArgs.UserToken = socket; if (!socket.SendAsync(sendEventArgs)) { ProcessSend(sendEventArgs); } } private void CloseClientSocket(AsyncUserToken userToken) { try { userToken.Socket.Shutdown(SocketShutdown.Send); } catch (Exception) { } userToken.Socket.Close(); m_readWritePool.Push(userToken.ReadEventArgs); m_maxAcceptedClients.Release(); } private byte[] HandleRequest(byte[] request) { // 处理请求并响应 return null; } } public class AsyncUserToken { public Socket Socket { get; set; } public List<byte> Data { get; set; } public SocketAsyncEventArgs ReadEventArgs { get; set; } public AsyncUserToken() { Data = new List<byte>(); } } ``` 以上示例代码演示了如何使用SocketAsyncEventArgs实现一个简单的Socket服务端,其中包含了异步接收、异步发送和连接池等功能。当有客户端连接时,它会从连接池中获取一个SocketAsyncEventArgs对象,并使用它来进行通信。在通信完成后,它会将SocketAsyncEventArgs对象放回连接池中,以便于重用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值