TCPConn.cs 11.3 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2 3 4 5 6
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
7
using System.Diagnostics;
潘栩锋's avatar
潘栩锋 committed
8 9 10

namespace FObjBase
{
11 12 13 14 15 16
    /// <summary>
    /// 解码
    /// </summary>
    /// <param name="packet"></param>
    /// <param name="conn"></param>
    /// <returns></returns>
潘栩锋's avatar
潘栩锋 committed
17
    public delegate bool ParsePacketHandler(byte[] packet, IFConn conn);
18 19 20 21

    /// <summary>
    /// 
    /// </summary>
潘栩锋's avatar
潘栩锋 committed
22 23
    public class TCPConn:IFConn
    {
潘栩锋's avatar
潘栩锋 committed
24
        static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
25 26 27
        /// <summary>
        /// 需要CRC校验
        /// </summary>
潘栩锋's avatar
潘栩锋 committed
28 29 30 31 32
        public bool HasCRC = false;

        TimeSpan Heartbeat_Interval = TimeSpan.FromSeconds(3);         // heartbeat包发送间隔时间,3秒
        TimeSpan Silent_Time = TimeSpan.FromSeconds(10);                // 单位ms没有收到任何东西的时间,10秒
        const int MAX_BUFFER = 20 * 0x4000;//20个大包, 大包的尺寸在FObjSys 定义
33 34 35 36 37 38 39 40 41 42 43 44
        List<byte> in_buffer = new List<byte>(MAX_BUFFER);
        List<byte> out_buffer = new List<byte>(MAX_BUFFER);

        /// <summary>
        /// 通信超时判断
        /// </summary>
        Stopwatch stopwatch_comm = new Stopwatch();

        /// <summary>
        /// 心跳包判断
        /// </summary>
        Stopwatch stopwatch_heatbeat = new Stopwatch();
潘栩锋's avatar
潘栩锋 committed
45

46 47 48 49

        /// <summary>
        /// 
        /// </summary>
潘栩锋's avatar
潘栩锋 committed
50 51
        public ParsePacketHandler ParsePacket = null;

52 53 54
        /// <summary>
        /// 
        /// </summary>
潘栩锋's avatar
潘栩锋 committed
55 56
        public Socket sock;
      
57 58 59
        /// <summary>
        /// 
        /// </summary>
潘栩锋's avatar
潘栩锋 committed
60 61
        protected bool first_poll=true;

62 63 64
        /// <summary>
        /// 
        /// </summary>
潘栩锋's avatar
潘栩锋 committed
65 66 67 68
        public TCPConn() 
        {
        
        }
69 70 71 72
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sock"></param>
潘栩锋's avatar
潘栩锋 committed
73 74 75 76 77
        public TCPConn(Socket sock) 
        {
            this.sock = sock;
        }

78 79 80 81 82
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
潘栩锋's avatar
潘栩锋 committed
83 84
        public virtual int SendPacket(byte[] buffer)
        {
85 86 87 88 89 90 91 92
            lock (out_buffer)
            {
                int len = buffer.Length;

                out_buffer.AddRange(buffer);

                return len;
            }
潘栩锋's avatar
潘栩锋 committed
93
        }
潘栩锋's avatar
潘栩锋 committed
94

95 96 97 98
        /// <summary>
        /// 从包提取数据
        /// </summary>
        /// <returns></returns>
潘栩锋's avatar
潘栩锋 committed
99 100
        protected virtual int GetRecvInfoPacket()   // return length of the packet
        {
潘栩锋's avatar
潘栩锋 committed
101
            int len = in_buffer.Count();
潘栩锋's avatar
潘栩锋 committed
102 103 104
            if (len < 2) return 0;
            byte[] bs = new byte[2];

潘栩锋's avatar
潘栩锋 committed
105 106 107 108
            int plen = BitConverter.ToUInt16(in_buffer.GetRange(0, 2).ToArray(), 0);

            if (plen > 0x4000 * 2)
            {
潘栩锋's avatar
潘栩锋 committed
109 110
                //包太大,不正常!!!!!!
                //断开重新连接
潘栩锋's avatar
潘栩锋 committed
111
                logger.Error("TCPConn GetRecvInfoPacket 包太大,不正常, 断开重新连接");
潘栩锋's avatar
潘栩锋 committed
112
                sock.Close();
潘栩锋's avatar
潘栩锋 committed
113

潘栩锋's avatar
潘栩锋 committed
114 115
                return -1;
            }
116 117 118 119
            else if (plen < 2) {
                //异常,包最短也有2个byte
                logger.Error($"TCPConn GetRecvInfoPacket 包.Size = {plen},太小,不正常, 断开重新连接");
                sock.Close();
潘栩锋's avatar
潘栩锋 committed
120

121 122
                return -1;
            }
潘栩锋's avatar
潘栩锋 committed
123 124 125 126 127 128 129
            if (len < plen)
            {
                return 0;
            }

            if (HasCRC) //TODO
            {
130 131 132 133 134 135 136 137
                
                if (plen < 4) {
                    //
                    logger.Error("TCPConn GetRecvInfoPacket 包.Size < 4, 无法 CRC 校验。  断开重新连接");
                    sock.Close();
                    return -1;
                }

潘栩锋's avatar
潘栩锋 committed
138 139
                UInt16 crc = Misc.CRC.CRC16(in_buffer, 0, plen - 2);
                int packet_crc_idx = plen - 2;
潘栩锋's avatar
潘栩锋 committed
140 141 142
                UInt16 packet_crc = BitConverter.ToUInt16(in_buffer.GetRange(packet_crc_idx, 2).ToArray(), 0);
                if (crc != packet_crc)
                {
潘栩锋's avatar
潘栩锋 committed
143
                    logger.Error("TCPConn GetRecvInfoPacket CRC != packet_crc 断开重新连接");
潘栩锋's avatar
潘栩锋 committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157
                    //断开重新连接
                    sock.Close();
                    return -1;
                }
            }



            if (len >= plen)
            {
                return plen;
            }
            return 0;
        }
潘栩锋's avatar
潘栩锋 committed
158
 
159 160 161 162 163
        /// <summary>
        /// 解包
        /// </summary>
        /// <param name="len"></param>
        /// <returns></returns>
潘栩锋's avatar
潘栩锋 committed
164
        protected virtual bool Parse_Packet(int len)
潘栩锋's avatar
潘栩锋 committed
165
        {
潘栩锋's avatar
潘栩锋 committed
166 167
            byte[] packet = in_buffer.GetRange(0, len).ToArray();
            in_buffer.RemoveRange(0, len);
潘栩锋's avatar
潘栩锋 committed
168 169
            return ParsePacket(packet, this);
        }
潘栩锋's avatar
潘栩锋 committed
170
        
171 172 173
        /// <summary>
        /// 发送心跳包
        /// </summary>
潘栩锋's avatar
潘栩锋 committed
174 175 176 177 178 179 180 181 182 183 184 185
        void Send_HeartBeat()
        {
            byte[] buf = new byte[2];
            buf[0] = 0x02;
            buf[1] = 0x00;
            SendPacket(buf);
            return;
        }
        int Send_Poll2() 
        {
            if (out_buffer.Count() == 0)
            {
186
                if (stopwatch_heatbeat.Elapsed > Heartbeat_Interval)
潘栩锋's avatar
潘栩锋 committed
187
                {
潘栩锋's avatar
潘栩锋 committed
188
                    Send_HeartBeat();//是时候把心跳包放入发送缓存!!!
潘栩锋's avatar
潘栩锋 committed
189 190 191 192
                }
                else
                    return 0;
            }
193
            stopwatch_heatbeat.Restart();
潘栩锋's avatar
潘栩锋 committed
194 195 196 197
            return Send_Poll();
        }
        int Send_Poll()
        {
198
            
潘栩锋's avatar
潘栩锋 committed
199
            if (out_buffer.Count() == 0)//没数据,直接返回
潘栩锋's avatar
潘栩锋 committed
200
                return 0;
201 202 203
            lock (out_buffer) {
                int cnt_total = 0;
                while (out_buffer.Count() > 0)//只有有数据发送,且能发送,没有 block, 就会一直循环
潘栩锋's avatar
潘栩锋 committed
204
                {
205 206 207 208 209 210 211 212 213
                    int cnt;
                    try
                    {
                        cnt = sock.Send(out_buffer.ToArray());
                    }
                    catch (System.Net.Sockets.SocketException e)
                    {
                        if (e.SocketErrorCode == SocketError.WouldBlock)//当前发不了,退出循环,等下次!!!!
                            break;
214
                        logger.Error(e, "TCPConn Send_Poll 发送异常");
215 216
                        return -1;//异常,断开连接!!!
                    }
潘栩锋's avatar
潘栩锋 committed
217

218 219 220 221 222 223 224 225 226
                    if (cnt > 0)
                    {
                        out_buffer.RemoveRange(0, cnt);//发送成功,删除!!!
                        cnt_total+=cnt;
                    }
                    else
                    {
                        break;
                    }
潘栩锋's avatar
潘栩锋 committed
227
                }
228
                return cnt_total;//返回总发送量
潘栩锋's avatar
潘栩锋 committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
            }
        }
        
        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)
潘栩锋's avatar
潘栩锋 committed
246
                    {
247
                        logger.Error(e,"TCPConn Receive_Poll 什么都收不到");
潘栩锋's avatar
潘栩锋 committed
248
                        return -1;
潘栩锋's avatar
潘栩锋 committed
249
                    }
潘栩锋's avatar
潘栩锋 committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
                    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)
潘栩锋's avatar
潘栩锋 committed
266
                    {
267
                        logger.Error(e, "TCPConn Receive_Poll 什么都收不到");
潘栩锋's avatar
潘栩锋 committed
268
                        return -1;
潘栩锋's avatar
潘栩锋 committed
269
                    }
潘栩锋's avatar
潘栩锋 committed
270 271 272 273 274 275 276 277
                    else
                        return reclen_total;
                }
                if (reclen > 0)
                {
                    in_buffer.AddRange(buf);
                    reclen_total += reclen;

278
                    stopwatch_comm.Restart();
潘栩锋's avatar
潘栩锋 committed
279 280 281 282 283 284 285
                }
            }
        }
        protected void Init() 
        {
            if (first_poll)
            {
286 287
                stopwatch_comm.Restart();
                stopwatch_heatbeat.Restart();
潘栩锋's avatar
潘栩锋 committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
                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)
            {
304
                if (stopwatch_comm.Elapsed > Silent_Time)
潘栩锋's avatar
潘栩锋 committed
305
                {
潘栩锋's avatar
潘栩锋 committed
306
                    logger.Error("TCPConn OnPoll 长时间没收到任何数据 断开连接");
潘栩锋's avatar
潘栩锋 committed
307

潘栩锋's avatar
潘栩锋 committed
308 309 310 311 312 313 314 315
                    ret = -2;
                    goto end;
                }
            }
            else
            {
                while (true)
                {
潘栩锋's avatar
潘栩锋 committed
316
                    int packet_len = GetRecvInfoPacket();
潘栩锋's avatar
潘栩锋 committed
317 318
                    if (packet_len > 0)
                    {
潘栩锋's avatar
潘栩锋 committed
319
                        Parse_Packet(packet_len);
潘栩锋's avatar
潘栩锋 committed
320 321 322 323 324 325 326
                    }
                    else if (packet_len == 0)
                    {
                        break;
                    }
                    else 
                    {
潘栩锋's avatar
潘栩锋 committed
327
                        //异常
潘栩锋's avatar
潘栩锋 committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341
                        ret = -1;
                        goto end;
                    }
                }
            }
            int sendlen = Send_Poll2();

            if (sendlen < 0)
            {
                ret = -1;
                goto end;
            }
        end:
            if (ret != 0)
潘栩锋's avatar
潘栩锋 committed
342 343
            {
                //连接断开,清空接收缓存区
潘栩锋's avatar
潘栩锋 committed
344
                logger.Error("TCPConn OnPoll 连接断开,清空接收缓存区");
潘栩锋's avatar
潘栩锋 committed
345 346

                in_buffer.Clear();
347 348 349 350
                lock(out_buffer)
                {
                    out_buffer.Clear();
                }
潘栩锋's avatar
潘栩锋 committed
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
                Enable = false;
            }
            return ret;
        }

        #region IFConn 成员

        public ConnectHandler ConnectAction
        {
            get;
            set;
        }
        protected bool isconnected = false;
        public virtual bool IsConnected
        {
            get {
                return isconnected;
            }
            set {
                if (isconnected != value) 
                {
                    isconnected = value;
                    ConnectAction(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
    }
}