• Common.TcpLibTcpClientS


    using System;
    using System.Text;
    using System.Collections;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Runtime.InteropServices;
    using System.IO;

    namespace Common.TcpLib
    {
        /// <summary>
        /// 同步Socket处理客户端 专用于短连接处理
        /// </summary>
        public class TcpClientS
        {
            public Socket _clientSocket;
            private string _serverIp;
            private int _port;
            private int _bufferSize = 1024;

            private bool _disposed = false;
            private bool _debug = false;

            #region define delegates
            /// <summary>
            /// 连接上服务器后的事件处理
            /// </summary>
            public _Bgz_OnConnectEventDelegate FOnConnectEventDelegate;

            /// <summary>
            /// 接收服务端发来的数据事件处理
            /// </summary>
            public _Bgz_OnReceiveBeginEventDelegate FOnReceiveBeginEventDelegate;

            /// <summary>
            /// 接收服务端发来的数据事件处理
            /// </summary>
            public _Bgz_OnReceiveingEventDelegate FOnReceiveingEventDelegate;

            /// <summary>
            /// 接收服务端发来的数据事件处理
            /// </summary>
            public _Bgz_OnReceiveEndEventDelegate FOnReceiveEndEventDelegate;

            /// <summary>
            /// 报错信息处理
            /// </summary>
            public _Bgz_OnErrorEventDelegate FOnErrorEventDelegate;
            #endregion

            #region Event
            private void OnConnectEvent(_Bgz_ConnectionState state)
            {
                if (FOnConnectEventDelegate != null) FOnConnectEventDelegate(state);
            }
            private void OnReceiveBeginEvent(_Bgz_ConnectionState state)
            {
                if (FOnReceiveBeginEventDelegate != null) FOnReceiveBeginEventDelegate(state);
            }
            private void OnReceiveingEvent(_Bgz_ConnectionState state)
            {
                if (FOnReceiveingEventDelegate != null) FOnReceiveingEventDelegate(state);
            }
            private void OnReceiveEndEvent(_Bgz_ConnectionState state)
            {
                if (FOnReceiveEndEventDelegate != null) FOnReceiveEndEventDelegate(state);
            }
            private void OnErrorEvent(ErrorType errortype, string msg, _Bgz_ConnectionState state)
            {
                if (FOnErrorEventDelegate != null) FOnErrorEventDelegate(errortype, msg, state);
            }
            #endregion

            #region property

            public int BufferSize
            {
                get
                {
                    return _bufferSize;
                }
            }

            public bool Debug
            {
                get
                {
                    return _debug;
                }
                set
                {
                    _debug = value;
                }
            }
            #endregion

            #region Constructor and Destructor

            public TcpClientS(string serverIp, int port)
            {
                this._serverIp = serverIp;
                this._port = port;
            }

            public TcpClientS(string serverIp, int port, int bufferSize)
            {
                this._serverIp = serverIp;
                this._port = port;
                this._bufferSize = bufferSize;
            }

            ~TcpClientS()
            {
            }
            #endregion

            #region Private Methods
            private void Dispose()
            {
                if (!_disposed)
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    this.FOnConnectEventDelegate = null;
                    this.FOnErrorEventDelegate = null;
                    this.FOnReceiveBeginEventDelegate = null;
                    this.FOnReceiveEndEventDelegate = null;
                    this.FOnReceiveingEventDelegate = null;
                    _disposed = true;
                }
            }
            #endregion

            #region Public Methods

            public byte[] SendAsOdian(byte[] msg)
            {
                return SendAsOdian(msg, 60000);
            }

            public byte[] SendAsOdian(byte[] msg, int ReceiveTimeout)
            {

                #region 阻止Socket发送空字节信息
                if (msg == null || msg.Length == 0) return null;
                #endregion

                _Bgz_ConnectionState stx = new _Bgz_ConnectionState();

                #region Connect
                try
                {
                    stx._conn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    stx._conn.Connect(new IPEndPoint(IPAddress.Parse(_serverIp), _port));
                    stx._conn.LingerState = new LingerOption(false, 3);

                    #region 设置Socket接收延时的处理
                    stx._conn.ReceiveTimeout = ReceiveTimeout;
                    #endregion

                    OnConnectEvent(stx);
                }
                catch (Exception ex)
                {
                    if (Debug)
                    {
                        OnErrorEvent(ErrorType.Catch, "SendAsOdian.1 Error![Message]:\r\n" + ex.Message + "[StackTrace]:\r\n" + ex.StackTrace + "\r\n", null);
                    }
                    return null;
                }
                #endregion

                try
                {
                    stx._conn.Send(msg);

                    #region read to bytes

                    stx._buffer = new byte[0];
                    stx._count = 0;
                    stx._getonceall = false;
                    stx._conn.Receive(stx._buffer);

                    if (stx._conn.Available == 0)
                    {
                        if (Debug)
                        {
                            OnErrorEvent(ErrorType.Catch, "关闭与服务器的连接!", null);
                        }
                        stx._conn.Shutdown(SocketShutdown.Both);
                        stx._conn.Close();
                        return stx._buffer;
                    }

                    OnReceiveBeginEvent(stx);

                    stx._count = 0;
                    stx._dataStream.SetLength(0);
                    stx._dataStream.Position = 0;
                    if (stx._getonceall)
                    {
                        stx._buffer = new byte[stx._conn.Available];
                        int ret = stx._conn.Receive(stx._buffer, 0, stx._buffer.Length, SocketFlags.None);
                        if (ret > 0)
                        {
                            stx._dataStream.Write(stx._buffer, 0, stx._buffer.Length);
                            stx._count++;
                            OnReceiveingEvent(stx);
                        }
                    }
                    else
                    {
                        while (stx._conn.Available > 0)
                        {
                            if (stx._conn.Available > this._bufferSize)
                                stx._buffer = new byte[this._bufferSize];
                            else
                                stx._buffer = new byte[stx._conn.Available];
                            int ret = stx._conn.Receive(stx._buffer, 0, stx._buffer.Length, SocketFlags.None);
                            if (ret > 0)
                            {
                                stx._dataStream.Write(stx._buffer, 0, stx._buffer.Length);
                                stx._count++;
                                OnReceiveingEvent(stx);
                            }
                        }
                    }

                    OnReceiveEndEvent(stx);
                    #endregion


                }
                catch (Exception ex)
                {
                    if (Debug)
                    {
                        OnErrorEvent(ErrorType.Catch, "SendAsOdian.2 Error![Message]:\r\n" + ex.Message + "[StackTrace]:\r\n" + ex.StackTrace + "\r\n", null);
                    }
                }
                finally
                {
                    if (stx._conn != null)
                        if (stx._conn.Connected)
                        {
                            stx._conn.Shutdown(SocketShutdown.Both);
                            stx._conn.Close();
                        }
                    OnErrorEvent(ErrorType.DisConnect, "关闭与服务器的连接!", null);
                }

                return stx._buffer;
            }

            #endregion
        }

    }

  • 相关阅读:
    python基础学习(九)
    python基础学习(八)
    python基础学习(七)
    python基础学习(六)
    python基础学习(五)
    python基础学习(四)
    python基础学习(三)
    mysql-binlog server的实现
    percona-toolkit常用工具
    Linux下如何快速定位系统瓶颈在哪里
  • 原文地址:https://www.cnblogs.com/bigmouthz/p/946189.html
Copyright © 2020-2023  润新知