C#SocketAsyncEventArgs实现高效能多并发TCPSocket通信 (客户端实现)

本文档介绍了如何在C#中利用SocketAsyncEventArgs实现客户端的高效能多并发TCP通信。通过创建自定义的MySocketEventArgs类和使用BufferManager类,确保在多线程环境下可以同时处理多个请求,避免同步操作导致的性能瓶颈。提供了完整的代码示例,以帮助读者理解如何构建和使用此类实现异步TCP通信。
摘要由CSDN通过智能技术生成

    上一篇讲了服务器端的实现, 这一篇就是客户端的实现.

    服务器实现参考:《C#如何利用SocketAsyncEventArgs实现高效能TCPSocket通信 (服务器实现)》

     与服务器不同的是客户端的实现需要多个SocketAsyncEventArgs共同协作,至少需要两个:接收的只需要一个,发送的需要一个,也可以多个,这在多线程中尤为重要,接下来说明。

 

     客户端一般需要数据的时候,就要发起请求,在多线程环境中,请求服务器一般不希望列队等候,这样会大大拖慢程序的处理。如果发送数据包的SocketAsyncEventArgs只有一个,且当他正在工作的时候, 下一个请求也来访问,这时会抛出异常, 提示当前的套接字正在工作, 所以这不是我们愿意看到, 唯有增加SocketAsyncEventArgs对象来解决。 那么接下来的问题就是我怎么知道当前的SocketAsyncEventArgs对象是否正在工作呢. 很简单,我们新建一个MySocketEventArgs类来继承它。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;

namespace Plates.Client.Net
{
    class MySocketEventArgs : SocketAsyncEventArgs
    {

        /// <summary>
        /// 标识,只是一个编号而已
        /// </summary>
        public int ArgsTag { get; set; }

        /// <summary>
        /// 设置/获取使用状态
        /// </summary>
        public bool IsUsing { get; set; }

    }
}

 

     接下来,我们还需要BufferManager类,这个类已经在服务端贴出来了,与服务端是一样的, 再贴一次:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Plates.Client.Net
{
    class BufferManager
    {
        int m_numBytes;                 // the total number of bytes controlled by the buffer pool
        byte[] m_buffer;                // the underlying byte array maintained by the Buffer Manager
        Stack<int> m_freeIndexPool;     // 
        int m_currentIndex;
        int m_bufferSize;

        public BufferManager(int totalBytes, int bufferSize)
        {
            m_numBytes = totalBytes;
            m_currentIndex = 0;
            m_bufferSize = bufferSize;
            m_freeIndexPool = new Stack<int>();
        }

        // Allocates buffer space used by the buffer pool
        public void InitBuffer()
        {
            // create one big large buffer and divide that 
            // out to each SocketAsyncEventArg object
            m_buffer = new byte[m_numBytes];
        }

        // Assigns a buffer from the buffer pool to the 
        // specified SocketAsyncEventArgs object
        //
        // <returns>true if the buffer was successfully set, else false</returns>
        public bool SetBuffer(SocketAsyncEventArgs args)
        {

            if (m_freeIndexPool.Count > 0)
            {
                args.SetBuffer(m_buffer, m_freeIndexPool.Pop(), m_bufferSize);
            }
            else
            {
                if ((m_numBytes - m_bufferSize) < m_currentIndex)
                {
                    return false;
                }
                args.SetBuffer(m_buffer, m_currentIndex, m_bufferSize);
                m_currentIndex += m_bufferSize;
            }
            return true;
        }

        // Removes the buffer from a SocketAsyncEventArg object.  
        // This frees the buffer back to the buffer pool
        public void FreeBuffer(SocketAsyncEventArgs args)
        {
            m_freeIndexPool.Push(args.Offset);
            args.SetBuffer(null, 0, 0);
        }
    }
}

 

     接下来是重点实现了,别的不多说,看代码:

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Plates.Client.Net
{
    class SocketManager: IDisposable
    {
        private const Int32 BuffSize = 1024;

        // The socket used to send/receive messages.
        private Socket clientSocket;

        // Flag for connected socket.
        private Boolean connected = false;

        // Listener endpoint.
        private IPEndPoint hostEndPoint;

        //
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值