TCPConn.cs 7.11 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace TCPManager
{
    /// <summary>
    /// 处理接收回来的数据,返回处理完的总字节数。 
    /// </summary>
    /// <param name="conn"></param>
    /// <param name="inBuf">从[0] 开始处理</param>
    /// <returns></returns>
    public delegate int ParsePacketHandler(TCPConn conn, byte[] inBuf);

    public class TCPConn
    {
        TimeSpan Heartbeat_Interval = TimeSpan.FromSeconds(5);         // heartbeat包发送间隔时间,5秒
        TimeSpan Silent_Time = TimeSpan.FromSeconds(30);                // 单位ms没有收到任何东西的时间,1分钟
        const int MAX_BUFFER = 20 * 0x4000;//20个大包, 大包的尺寸在FObjSys 定义
        const int Send_Error_timer = 5000;           // 5000ms
        protected List<byte> in_buffer = new List<byte>(MAX_BUFFER);
        protected int packet_start;
        protected int packet_len;

        protected List<byte> out_buffer = new List<byte>(MAX_BUFFER);
        protected DateTime comm_time;
        protected DateTime heartbeat_time = DateTime.Now;

        /// <summary>
        /// 长时间没发东西事件
        /// </summary>
        public event Action<TCPConn> OutputIsEmptyWithLongTimeEvent;
        /// <summary>
        /// 数据接收处理
        /// </summary>
        public ParsePacketHandler ParsePacket = null;

        public Socket sock;

        protected bool first_poll = true;

        public TCPConn()
        {

        }
        public TCPConn(Socket sock)
        {
            this.sock = sock;
        }

        public virtual int SendPacket(byte[] buffer)
        {
            int len = buffer.Length;
            out_buffer.AddRange(buffer);
            return len;
        }


        protected virtual int Clear_Packet()
        {
            if (packet_start > 0)
            {
                in_buffer.RemoveRange(0, packet_start);
            }
            return in_buffer.Count();
        }

        int Send_Poll2()
        {
            if (out_buffer.Count() == 0)
            {
                if ((DateTime.Now - heartbeat_time) > Heartbeat_Interval)
                {
                    if (OutputIsEmptyWithLongTimeEvent != null)
                        OutputIsEmptyWithLongTimeEvent(this);
                }
                else
                    return 0;
            }

            heartbeat_time = DateTime.Now;
            return Send_Poll();
        }
        int Send_Poll()
        {
            int cnt_total = 0;
            if (out_buffer.Count() == 0)
                return 0;

            while (out_buffer.Count() > 0)
            {
                int cnt;
                try
                {
                    cnt = sock.Send(out_buffer.ToArray());
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.WouldBlock)
                        break;
                    return -1;
                }

                if (cnt > 0)
                {
                    out_buffer.RemoveRange(0, cnt);
                    cnt_total += cnt;
                }
                else
                {
                    break;
                }
            }
            return cnt_total;
        }

        int Receive_Poll()
        {
            int reclen_total = 0;
            while (true)
            {
                int reclen;
                try
                {
                    reclen = sock.Available;
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    //FDEBUG.Debug.LogMessage(this, 10, "Receive_Poll e=" + e.ToString());
                    if (reclen_total == 0)
                        return -1;
                    else
                        return reclen_total;
                }

                if (reclen == 0)
                    return reclen_total;

                byte[] buf = new byte[reclen];
                try
                {
                    reclen = sock.Receive(buf);
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    //FDEBUG.Debug.LogMessage(this, 10, "Receive_Poll e=" + e.ToString());
                    if (reclen_total == 0)
                        return -1;
                    else
                        return reclen_total;
                }
                if (reclen > 0)
                {
                    in_buffer.AddRange(buf);
                    reclen_total += reclen;

                    comm_time = DateTime.Now;
                }
            }
        }
        protected void Init()
        {
            if (first_poll)
            {
                comm_time = DateTime.Now;
                heartbeat_time = DateTime.Now;
                first_poll = false;
            }
        }

        public virtual int OnPoll()
        {
            int ret = 0;
            Init();

            int reclen = Receive_Poll();
            if (reclen < 0)
            {
                ret = -1;
                goto end;
            }
            else if (reclen == 0)
            {
                if ((DateTime.Now - comm_time) > Silent_Time)//长时间没收到东西
                {
                    //FDEBUG.Debug.LogMessage(this, 10, "ERROR 超时出错!");
                    ret = -2;
                    goto end;
                }
            }
            else
            {
                int len=ParsePacket(this,in_buffer.ToArray());
                if (len > 0)
                {
                    in_buffer.RemoveRange(0, len);
                }
            }


            int sendlen = Send_Poll2();

            if (sendlen < 0)
            {

                ret = -1;
                goto end;
            }
        end:

            if (ret != 0)
            {
                //连接断开
                Enable = false;
            }
            return ret;
        }

        #region IFConn 成员

        public event Action<TCPConn> ConnectEvent;
        
        protected bool isconnected = false;
        public virtual bool IsConnected
        {
            get
            {
                return isconnected;
            }
            set
            {
                if (isconnected != value)
                {
                    isconnected = value;
                    if (ConnectEvent != null)
                        ConnectEvent(this);
                }
            }
        }


        protected bool enable = false;
        public bool Enable
        {
            get
            {
                return enable;
            }
            set
            {
                enable = value;
                if (enable == false)
                {
                    Stop();
                }
            }
        }
        protected virtual void Stop()
        {
            if (sock != null)
                sock.Close();
            IsConnected = false;
        }
        #endregion

        #region IFConn 成员


        public uint TranID
        {
            get;
            set;
        }

        #endregion
    }
}