GComm_TcpServer.cs 7.25 KB
Newer Older
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace GeneralGommunication
{
    public class GComm_TcpServer : IGeneralComm,IDisposable
    {
        /// <summary>
        /// IP 地址 and 端口号
        /// </summary>
        public string Addr { get; set; }

        IPEndPoint LocalEp => Misc.StringConverter.ToIPEndPoint(Addr);

        /// <summary>
        /// 是否异常
        /// </summary>
        public bool IsError => !string.IsNullOrEmpty(ErrMsg);

        /// <summary>
        /// 异常信息
        /// </summary>
        public string ErrMsg { get; private set; }

        /// <summary>
        /// 运行中
        /// </summary>
        public bool IsRunning { get; private set; }

        /// <summary>
        /// 连接成功
        /// </summary>
        public bool IsConnected { get; private set; }

        /// <summary>
        /// 接收task调用
        /// </summary>
        public event IGeneralCommDataReceivedHandler DataReceived;



        public event PropertyChangedEventHandler PropertyChanged;

        Socket sock;
        CancellationTokenSource cts_readTask;
        CancellationTokenSource cts_waitForSend;
        CancellationTokenSource cts_sendTask;

        public GComm_TcpServer(Socket sock)
        {
            this.sock = sock;
            IsConnected = true;
        }
        /// <summary>
        /// 开始
        /// </summary>
        public void Start()
        { 
            if (IsRunning)
                return;
            
            IsRunning = true;
            cts_readTask = new CancellationTokenSource();

            
            Task.Factory.StartNew(OnTask, cts_readTask.Token);
        }

        /// <summary>
        /// 接收
        /// </summary>
        public void Stop()
        {
            if (!IsRunning)
                return;
            IsRunning = false;
            IsConnected = false;
            cts_readTask.Cancel();
            if (sock != null && sock.Connected)
            {
                sock.Close();
                sock = null;
            }
        }

        void OnTask()
        {
            sendBuf.Clear();
            //启动发送task
            cts_sendTask = new CancellationTokenSource();
            var sendtask = Task.Factory.StartNew(SendTask, cts_sendTask.Token);

            //进入接收task
            ReceiveTask();

            //退出了,肯定连接断开了
            //需要等待 SendTask 也退出了
            cts_sendTask.Cancel();
            sendtask.Wait();

            if (sock != null)
            {
                sock.Close();
                sock = null;
            }

            IsConnected = false;
            IsRunning = false;
        }



        /// <summary>
        /// 接收任务
        /// </summary>
        void ReceiveTask()
        {
            byte[] buf = new byte[0x10000];
            while (!cts_readTask.IsCancellationRequested)
            {
                int len;
                try
                {
                    len = sock.Receive(buf);
                    if (len == 0)
                    {
                        continue;//没收到数据,继续等
                    }
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.TimedOut)
                        continue;//超时而已
                    else if ((e.SocketErrorCode == SocketError.ConnectionAborted)
                        || (e.SocketErrorCode == SocketError.ConnectionRefused)
                        || (e.SocketErrorCode == SocketError.ConnectionReset))
                    {
                        IsConnected = false;
                        return;
                    }
                    //Console.WriteLine($"ReceiveTask() {e}");
                    //肯定断开连接了
                    IsConnected = false;
                    break;
                }

                DataReceived?.Invoke(this, buf.Take(len).ToArray());
            }

            IsConnected = false;
        }

        /// <summary>
        /// 发送任务
        /// </summary>
        void SendTask()
        {
            while (!cts_sendTask.IsCancellationRequested)
            {
                CancellationTokenSource cts3;

                while (true)
                {
                    byte[] buffer;
                    lock (sendBuf)
                    {
                        if (sendBuf.Count <= 0)
                            break;
                        buffer = sendBuf.ToArray();
                    }

                    int slen;
                    try
                    {
                        slen = sock.Send(buffer);
                    }
                    catch (Exception e)
                    {
                        //连接断开了
                        IsConnected = false;
                        break;
                    }

                    if (slen <= 0)
                    {
                        //连接断开了
                        IsConnected = false;
                        break;
                    }
                    else
                    {
                        lock (sendBuf)
                        {
                            sendBuf.RemoveRange(0, slen);
                        }
                    }
                }

                //重新等 下次被呼醒
                lock (sendBuf)
                {
                    // 呼醒 发送task
                    if (cts_waitForSend == null)
                    {
                        cts_waitForSend = new CancellationTokenSource();
                    }
                    //cts_waitForSend 与 cts_sendTask 合体, 任意一个都会呼醒 delay
                    cts3 = CancellationTokenSource.CreateLinkedTokenSource(cts_waitForSend.Token, cts_sendTask.Token);
                }
                try
                {
                    Task.Delay(-1, cts3.Token).Wait();
                }
                catch (Exception e)
                {
                    //被打断, 有数据需要发送
                }
                lock (sendBuf)
                {
                    cts_waitForSend = null;
                }
            }
        }
        /// <summary>
        /// 无限大,发送缓存
        /// </summary>
        List<byte> sendBuf = new List<byte>();

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="buf"></param>
        public void Write(IEnumerable<byte> buf)
        {
            if (!IsConnected)
                return;

            lock (sendBuf)
            {
                //放入,发送缓存区
                sendBuf.AddRange(buf);

                //呼醒 发送task
                if (cts_waitForSend == null)
                {
                    cts_waitForSend = new CancellationTokenSource();
                }
                cts_waitForSend.Cancel();
                
            }
        }

        /// <summary>
        /// 清空输入缓存
        /// </summary>
        public void DiscardInBuffer()
        {
            //TODO
        }

        public void Dispose()
        {
            Stop();
        }
    }
}