c# socket线程池实现

服务器端:

    

PoolServer.cs类

    

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;


namespace Net.Common.Pool
{
    /// <summary>
    /// 服务器
    /// 1.调用构造方法:
    ///   (1)加载参数:端口、最大活动数量
    ///    (2)启用PooledConnectionHandler线程,根据最大活动数量创建线程,并且全部启动
    ///   PooledConnectionHandler线程,读取pool池,判断池内是否为空,如果不为空,则让线程安全的读取池内的第一个,并且进行业务处理
    ///   2.开启服务
    ///    (1)将TcpListener对象初始化
    ///       (2)等待客户机的请求,调用AcceptConnections()方法
    ///
    ///         @author layicr
    /// </summary>
    public class PoolServer
    {
        /// <summary>
        /// 最大活动数量
        /// </summary>
        private int maxConnections;
        /// <summary>
        /// 最大活动数量
        /// </summary>
        public int MaxConnections
        {
            get { return maxConnections; }
            set { maxConnections = value; }
        }
        /// <summary>
        /// 端口
        /// </summary>
        private int port;
        /// <summary>
        /// 端口
        /// </summary>
        public int Port
        {
            get { return port; }
            set { port = value; }
        }
        /// <summary>
        /// 第几张网卡,默认为第一个,值为0
        /// </summary>
        private int addressIndex = 0;
        /// <summary>
        /// 第几张网卡,默认为第一个,值为0
        /// </summary>
        public int AddressIndex
        {
            get { return addressIndex; }
            set { addressIndex = value; }
        }


        /// <summary>
        /// 是否打开服务
        /// </summary>
        private bool reLease = false;

        /// <summary>
        /// 线程集合
        /// </summary>
        private List<Thread> listConnectionThread = new List<Thread>();

        private TcpListener listener = null;
        private TcpClient client = null;


        /// <summary>
        ///
        /// </summary>
        public PoolServer()
        {
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="port">端口</param>
        /// <param name="maxConnections">最大活动数量</param>
        public PoolServer(int port, int maxConnections)
        {
            this.port = port;
            this.maxConnections = maxConnections;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="addressIndex">第几张网卡</param>
        /// <param name="port">端口</param>
        /// <param name="maxConnections">最大活动数量</param>
        public PoolServer(int addressIndex, int port, int maxConnections)
        {
            this.addressIndex = addressIndex;
            this.port = port;
            this.maxConnections = maxConnections;
        }

/// <summary>
        /// 启动服务
/// </summary>
        public void ServerStart()
        {
            this.reLease = true;
            IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName()); //得到主机IP
            IPAddress iPAddress = IpEntry.AddressList[addressIndex];
            listener = new TcpListener(iPAddress, this.port);
            listener.Start();
            //开启线程
            SetUpHandlers();
            // 允许客户机连接到服务器,等待客户机请求
            AcceptConnections();
        }


        /// <summary>
        ///  停止服务
        /// </summary>
        public void ServerStop()
        {
            if (listener != null)
            {
                try
                {
                    listener.Stop();
                    listener = null;
                    //清空池数据
                    PoolConnectionHandler.pool.Clear();
                    reLease = false;
                    //让PooledConnectionHandler线程停止
                    foreach(Thread item in listConnectionThread)
                    {
                        //停止
                        item.Abort();
                    }
                    //清空
                    listConnectionThread.Clear();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }


        /// <summary>
        /// 允许客户机连接到服务器,等待客户机请求
        /// 1.开启一个线程
        /// </summary>
        private void AcceptConnections()
        {
            new Thread(ListenerStart).Start();
        }

        /// <summary>
        /// 允许客户机连接到服务器,等待客户机请求
        /// 2.判断当前reLease(是否启用服务)的值是否为true
        /// 如果没有启用服务,则线程关闭
        /// 如果启用服务,则开始等待客户机请求,如果受到了客户机的请求,则加入池中
        /// </summary>
        private void ListenerStart()
        {
            while (reLease)
            {
                try
                {
                    client = listener.AcceptTcpClient();
                    HandleConnection(client);
                }
                catch (Exception e)
                {
                    //
                    Console.WriteLine(e.Message);
                }
            }
        }

        /// <summary>
        /// 将请求加入池中
        /// </summary>
        /// <param name="client"></param>
        private void HandleConnection(TcpClient client)
        {
            PoolConnectionHandler.ProcessRequest(client);
        }


        /// <summary>
        ///  开启PooledConnectionHandler线程
        /// </summary>
        private void SetUpHandlers()
        {
            Thread thread = null;
            for (int i = 0; i < maxConnections; i++)
            {
                PoolConnectionHandler currentHandler = new PoolConnectionHandler();
                thread = new Thread(new ThreadStart(currentHandler.Run));
                thread.Name = "Thread(" + i+")";
                thread.Start();
                listConnectionThread.Add(thread);
            }
        }

    }
}

    

    

PoolConnectionHandler.cs类

    

using System;
using System.Collections.Generic;
using System.Text;


using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;


namespace Net.Common.Pool
{
    public class PoolConnectionHandler
    {
        /// <summary>
        ///  池
        /// </summary>
        public static LinkedList<TcpClient> pool = new LinkedList<TcpClient>();

        /// <summary>
        ///
        /// </summary>
        protected TcpClient client = null;

        /// <summary>
        ///
        /// </summary>
        public PoolConnectionHandler() { }

        /// <summary>
        /// 业务处理
        /// </summary>
        public void HandleConnection()
        {

            try
            {
                //这里调用,   业务层的方法

                HandleMain.Handle(client);

            }
            catch
            { }

        }


        /// <summary>
        /// 将未处理的请求加入池中
        /// </summary>
        /// <param name="requestToHandle"></param>
        public static void ProcessRequest(TcpClient requestToHandle)
        {
            //对池进行加锁
            lock (pool)
            {
                //把未处理的请求加入池
                pool.AddLast(requestToHandle);
                //将等待线程被唤醒
                Monitor.PulseAll(pool);
            }
        }

 

        /// <summary>
        ///  一直接读取pool(池),并且对pool进行加锁,判断其集合是否为空
        /// 如果pool为空,则一直的读取
        /// 如要pool不为空,则取出第一个值,到了这一步锁解除(保存池取值的过程是安全,取出的值是唯一),接着执行handleConnection
        /// </summary>
        public void Run()
        {
            while (true)
            {
                try
                {
                    lock (pool)
                    {
                        while (pool.Count == 0)
                        {
                            Monitor.Wait(pool);
                        }
                        //取第一个值
                        client = pool.First.Value;
                        //移除
                        pool.RemoveFirst();
                    }
                    HandleConnection();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
}

 

 

HandleMain.cs业务类:

using System;
using System.Collections.Generic;
using System.Text;


using System.Net;
using System.Net.Sockets;
using System.IO;

namespace Net.Common.Pool
{
    /// <summary>
    /// 业务类,测试类
    /// </summary>
   public  class HandleMain
    {
       public static void Handle(TcpClient client)
       {
           Console.WriteLine("当前线程:" + System.Threading.Thread.CurrentThread.Name);

           NetworkStream networkStream = null;
           //输入
           StreamReader streamReader = null;

           FileStream fileStream = null;
           byte[] buffer = null;

           int length = 3*1024;

           try
           {
               networkStream = client.GetStream();
               streamReader = new StreamReader(networkStream);

               //文件名
               string fileName = streamReader.ReadLine();

               fileStream = new FileStream(@"E:\1\" + fileName, FileMode.Create, FileAccess.Write);

               int readLength = 0;

            // int   sumLength = 0;
          //     DateTime myDtStart = DateTime.Now;

               buffer = new byte[length];

               while ((readLength = networkStream.Read(buffer, 0, length)) > 0)
               {
                   fileStream.Write(buffer, 0, readLength);
                   fileStream.Flush();

                   //总量
                   //   sumLength += readLength;
                   //double total = sumLength / 1000;

                   //    TimeSpan ts = DateTime.Now - myDtStart;
                   //当前速度
                   //     double speed = total / ts.TotalSeconds;
               }
               fileStream.Flush();
           }
           catch (Exception ex)
           {
               Console.WriteLine(ex.Message);
           }
           finally
           {
               if (fileStream != null)
               {
                   fileStream.Close();
               }
               if (streamReader != null)
               {
                   streamReader.Close();
               }
               if (networkStream != null)
               {
                   networkStream.Close();
               }
               if (client != null)
               {
                   client.Close();
               }
           }
       }
 
    }
}

                   

 

 

运行服务器端:

    int port = 3848;
    PoolServer poolServer = new PoolServer(port, 10);
    poolServer.ServerStart();                  

 

 

客户端测试:

using System.Net;
using System.IO;
using System.Net.Sockets;

 

 

public void Send(){

            string serverIP = "192.168.1.138";//服务器IP地址
            int port = 3848;//端口号
            string filePath = "c:\\1.jpg";//要传输的文件

           

 int length = 2048;

            TcpClient client = null;
            NetworkStream networkStream = null;
            FileStream fileStream = null;
            StreamWriter streamWriter = null;

            byte[] buffer = null;
            int readLength = 0;

            String msg = null;//传输消息
            string fileExt = null; //文件的后缀

            while (true)
            {
                System.Threading.Thread.Sleep(900);//很重要/
                try
                {
                    //连接服务器
                    client = new TcpClient(serverIP, port);

                    client.SendTimeout = 60 * 1000;//发送超时值,以毫秒为单位

                    networkStream = client.GetStream();

                    //输出
                    streamWriter = new StreamWriter(networkStream);

                    //输入
                    //  StreamReader sr = new StreamReader(networkStream);

                    fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);

                    //得到后缀,包括"."
                    fileExt = Path.GetExtension(filePath).ToLower();

                    //远程服务器生成的文件名称
                    msg = System.Guid.NewGuid().ToString() + fileExt;

                    //传输消息
                    streamWriter.WriteLine(msg);
                    streamWriter.Flush();

                    buffer = new byte[length];

                    while ((readLength = fileStream.Read(buffer, 0, length)) > 0)
                    {
                        networkStream.Write(buffer, 0, readLength);
                        networkStream.Flush();
                    }
                    networkStream.Flush();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                    if (streamWriter != null)
                    {
                        streamWriter.Close();
                    }
                    if (networkStream != null)
                    {
                        networkStream.Close();
                    }
                    if (client != null)
                    {
                        client.Close();
                    }
                }
            }

}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值