zoukankan      html  css  js  c++  java
  • Socket 代码收藏


        class SocketHelper
        {
            public delegate void Uplistbox(string txt);
            public Uplistbox uplb;  //更新listbox委托变量
            protected static readonly ILog logger = LogManager.GetLogger(typeof(TCPSocketServer2));
            private ManualResetEvent allDone = new ManualResetEvent(false); //线程控制
            protected Hashtable m_workerSocketHt = Hashtable.Synchronized(new Hashtable());//保存客户端socket哈希表
            public AsyncCallback asyncCallBack;  //声明异步完成时调用的方法.
            private Socket m_mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//主通信Socket
            public bool isExit = false;//全局控制SOCKET启动和关闭
            private long m_clientCount = 0L;//记录客户端数量
            /// <summary>
            /// 发送消息
            /// </summary>
            /// <param name="buffer">需要发送的字节</param>
            public void Send(byte[] buffer)
            {
                try
                {
                    //目标地址
                    IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
                    //发送通信socket
                    Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sk.Connect(ip);//连接
                    sk.Send(buffer);//发送
                    SocketUser su = new SocketUser();
                    su.CurrentSocket = sk;
                    su.DataBuffer = buffer;
                    //异步接收
                    asyncCallBack = new AsyncCallback(OnDataReceived);
                    sk.BeginReceive(su.DataBuffer, 0, su.DataBuffer.Length, SocketFlags.None, asyncCallBack, su);
                }
                catch (Exception ex)
                {
                    string msg = ex.ToString() + " " + DateTime.Now.ToString();
                    uplb(msg);
                    logger.Debug(msg);
                }
            }
            /// <summary>
            /// 发送消息[重载]
            /// </summary>
            /// <param name="SocketUser">需要发送的SocketUser对象</param>
            /// <param name="buffer">需要发送的字节</param>
            public void Send(SocketUser su, byte[] buffer)
            {
                try
                {
                    //目标地址
                    IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
                    //发送通信socket
                    su.CurrentSocket.Connect(ip);//连接
                    su.CurrentSocket.Send(buffer);//发送
                    su.DataBuffer = buffer;
                    //异步接收
                    asyncCallBack = new AsyncCallback(OnDataReceived);
                    su.CurrentSocket.BeginReceive(su.DataBuffer, 0, su.DataBuffer.Length, SocketFlags.None, asyncCallBack, su);
                }
                catch (Exception ex)
                {
                    string msg = ex.ToString() + " " + DateTime.Now.ToString();
                    uplb(msg);
                    logger.Debug(msg);
                }
            }
            /// <summary>
            /// 建立监听连接
            /// </summary>
            /// <param name="port">监听的端口号</param>
            private void AcceptConnection(object port)
            {
                try
                {
                    IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, (int)port);
                    //绑定地址
                    m_mainSocket.Bind(ipLocal);
                    //开始监听
                    m_mainSocket.Listen(10000);
                    while (isExit == false)
                    {
                        try
                        {
                            allDone.Reset(); //线程阻塞
                            logger.Debug("TcpListener启动成功: " + ipLocal.Address.ToString() + "," + ipLocal.Port.ToString());
                            //接收异步连接并创建新的socket对象.
                            m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), m_mainSocket);
                            allDone.WaitOne();
                        }
                        catch (SocketException sf)
                        {
                            logger.Error("客户连接请求异常" + sf.ToString());
                        }
                        catch (Exception f)
                        {
                            logger.Error("客户连接请求异常" + "错误信息:" + f.Message);
                            break;
                        }
                    }
                }
                catch (SocketException se)
                {
                    logger.Error("TcpListener启动失败" + se.ToString() + "错误号:" + se.ErrorCode.ToString());
                }
                catch (Exception e)
                {
                    logger.Error("TcpListener错误" + "错误信息:" + e.Message);
                }
            }
            /// <summary>
            /// 开始监听
            /// </summary>
            /// <param name="Port">监听的端口</param>
            /// <param name="buffer">发送的字节</param>
            public bool StartListening(int Port, params byte[] buffer)
            {
                if (Port == 0)
                {
                    logger.Debug("TcpListener未启动,请指定监听的端口号.");
                    return false;
                }
                // 创建监听socket
                Thread AcceptTh = new Thread(new ThreadStart(delegate
                {
                    AcceptConnection(Port);
                }));
                AcceptTh.Start();
                Thread sendth = new Thread(new ThreadStart(delegate
                {
                    Send(buffer);
                }));
                sendth.Start();
                logger.Debug("启动TCP监听,端口: " + Port);
                return true;
            }
          }
    }

  • 相关阅读:
    子网掩码的作用与IP网段的划分
    DHCP服务器
    Anaconda安装、更新第三方包
    time模块的使用
    TensorFlow安装
    机器学习-线性回归
    机器学习
    Pyhton-类(2)
    python-类(1)
    Python-函数
  • 原文地址:https://www.cnblogs.com/chengeng/p/4441894.html
Copyright © 2011-2022 走看看