网络IsAlive问题C#

时间:2018-04-04 17:30:59

标签: c#

目前我正在编程一个简单的聊天。对于网络,我使用网络观察器,它从流中读取并写入。出于安全原因,我想实现一个有效检查,在特定的时间间隔内,客户端向服务器发送消息,服务器向客户端发送消息。其方法称为" IsAliveWorker"它以自己的线程运行。但是如果对方收到消息,我在检查时间方面遇到了问题。一段时间后,它总是触发ConnectionLostEvent,只有在客户端或服务器断开连接而不通知对方之前才会触发(例如,当用户终止进程或计算机关闭时)。我真的不知道这里的问题是什么,但我认为这是一个时间问题。下面的代码来自客户端,但IsAliveWorker方法在服务器上是相同的,所以我只发布一次。我真的很感激如果有人会检查下面的代码,我现在已经搞乱了很长一段时间。 :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace Client
{
    public class NetworkWatcher
    {
        private TcpClient client;
        private NetworkStream stream;
        private IPEndPoint ipEndPoint;
        private bool isReading;
        private Thread readThread;
        private Thread isAliveThread;
        private bool isAlive;

        public event EventHandler<DataReceivedEventArgs> DataReceived;
        public event EventHandler<EventArgs> ConnectionLost;

        public NetworkWatcher(IPAddress ip, int port)
        {
            this.ipEndPoint = new IPEndPoint(ip, port);
            this.client = new TcpClient();
        }

        public bool Connected
        {
            get;
            private set;
        }

        public void Start()
        {
            try
            {
                if (this.client.ConnectAsync(this.ipEndPoint.Address, this.ipEndPoint.Port).Wait(1000) == false)
                {
                    throw new TimeoutException();
                }

                this.stream = this.client.GetStream();

                this.readThread = new Thread(Read);
                this.isReading = true;
                this.readThread.Start();
                this.Connected = true;

                this.isAliveThread = new Thread(this.IsAliveWorker);
                this.isAliveThread.Priority = ThreadPriority.Highest;
                this.isAliveThread.Start();
            }
            catch
            {
                this.FireOnConnectionLost();
            }
        }

        private void IsAliveWorker()
        {
            while (this.isReading == true)
            {
                this.Send(ProtocolCreator.IsAlive());

                Thread.Sleep(2000);

                if (this.isAlive == false)
                {
                    this.FireOnConnectionLost();
                }
                else
                {
                    this.isAlive = false;
                }
            }
        }

        public void Stop()
        {
            try
            {
                this.isReading = false;
                this.stream.Close();
                this.client.Close();
                this.client = new TcpClient();
                this.Connected = false;
            }
            catch
            {

            }
        }

        private void Read()
        {
            while (this.isReading == true)
            {
                if (this.stream.DataAvailable == false)
                {
                    Thread.Sleep(10);
                    continue;
                }

                List<byte> receivedBytes = new List<byte>();
                byte[] buffer = new byte[1];

                while (this.stream.DataAvailable == true)
                {
                    this.stream.Read(buffer, 0, 1);

                    if (buffer[0] == 127)
                    {
                        break;
                    }

                    receivedBytes.Add(buffer[0]);
                }

                if (receivedBytes.Count >= 6)
                {
                    if (receivedBytes[0] == 67 && receivedBytes[1] == 72 && receivedBytes[2] == 65 && receivedBytes[3] == 84)
                    {
                        if (receivedBytes[4] == 73 && receivedBytes[5] == 65)
                        {
                            this.isAlive = true;
                        }
                        else
                        {
                            this.FireOnDataReceived(receivedBytes.ToArray());
                        }
                    }
                }
            }
        }

        protected virtual void FireOnDataReceived(byte[] data)
        {
            if (this.DataReceived != null)
            {
                this.DataReceived(this, new DataReceivedEventArgs(data, this.client));
            }
        }

        protected virtual void FireOnConnectionLost()
        {
            if (this.ConnectionLost != null)
            {
                this.ConnectionLost(this, new EventArgs());
            }
        }

        public void Send(Protocol protocol)
        {
            try
            {
                byte[] sendBytes = protocol.ToByteArray();

                this.stream.Write(sendBytes, 0, sendBytes.Length);
            }
            catch
            {
                this.FireOnConnectionLost();
            }
        }
    }
}

0 个答案:

没有答案