简体   繁体   English

C#服务器客户端,客户端不重新连接

[英]c# server-client, client doesnt reconnect

thanks in advance for anything. 预先感谢任何事情。 Im making a server-client program, in which the server(application) creates a server and the client connects to it, i will also have a textbox and a button on the server application and whenever i write something on that textbox and press the button, it will send to the client application(there is only a textbox in this application, the only thing this application does is receive strings from the server application). 我正在制作一个服务器-客户端程序,其中服务器(应用程序)创建一个服务器,客户端连接到该服务器,我还将在服务器应用程序上有一个文本框和一个按钮,并且每当我在该文本框上写一些东西并按下按钮时,它将发送到客户端应用程序(此应用程序中只有一个文本框,此应用程序唯一要做的就是从服务器应用程序接收字符串)。

I think it works, kinda, but not the way i want it. 我认为它有效,但不是我想要的方式。 I can make the connection and also send and receive the information from the textboxs, but only if i run the server application first(to create the server). 我可以建立连接,也可以从文本框中发送和接收信息,但前提是我必须先运行服务器应用程序(以创建服务器)。 The problem is that if i dont run the server application first(to create the server), the client application won't connect, or even try to. 问题是,如果我不首先运行服务器应用程序(以创建服务器),则客户端应用程序将无法连接,甚至无法连接。

Example of "Error"(i guess you can call it an error): If i run the client application first and then the server application, the client application just won't connect to the server that the server application created, i made a loop that basically verifies if the client is cnnected, if it is then it starts receiving the information, if not(else) waits for 3 seconds and tries to reconnect again. “错误”的示例(我想您可以称其为错误):如果先运行客户端应用程序,然后再运行服务器应用程序,则客户端应用程序将无法连接至该服务器应用程序创建的服务器,因此发生了循环基本上验证客户端是否被连接,如果是,则它开始接收信息,否则,则等待3秒钟并尝试重新连接。 but when it tries to reconnect it doesnt work. 但是,当它尝试重新连接时,它不起作用。 Any ideas? 有任何想法吗?

CODE IN C#: C#中的代码:

    public Form1()
    {

        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e) //connect to server
    {
        client = new TcpClient();
        IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.34"), 123); // sincronizacao do IP com a porta
        try
        {

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IAsyncResult result = client.BeginConnect(IPAddress.Parse("192.168.254.34"), 123, null, null);
            bool success = result.AsyncWaitHandle.WaitOne(3000, true);

            while (success)
            {

                if (client.Connected)
                {

                    STW = new StreamWriter(client.GetStream());
                    STR = new StreamReader(client.GetStream());
                    STW.AutoFlush = true;

                    backgroundWorker1.RunWorkerAsync(); // Começar a receber dados em background
                    backgroundWorker1.WorkerSupportsCancellation = true; // possibilidade de cancelar o fio

                }
                else
                {

                    int milliseconds = 3000;
                    Thread.Sleep(milliseconds);
                    MessageBox.Show("swag do elias!");

                    client.Connect(IP_End);
                }
            }


        }
        catch (SocketException exception)
        {
            MessageBox.Show("O erro é:", exception.Source);
        }
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) // Receber dados
    {
        while(client.Connected) //enquanto o cliente tiver conectado vai ler o que servidor diz em chat 
        {
            try
            {
                receive = STR.ReadLine();
                this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.Text=(receive + "\n\r"); }));
                receive = "";
            }
            catch(Exception x)
            {
                MessageBox.Show(x.Message.ToString());
            }
        }
    }
}

} }

If the server isn't running yet, then success is always going to be false as a result of this line: 如果服务器尚未运行,则由于以下原因,成功总是错误的:

bool success = result.AsyncWaitHandle.WaitOne(3000, true);

Since success will always be false, the code inside of your while(success) block will never be executed. 由于成功总是错误的,因此while(success)块中的代码将永远不会执行。

Rearranging your code to something like this might be helpful: 将代码重新排列为类似以下内容可能会有所帮助:

client = new TcpClient();

bool success = false;
while (success == false)
{
    try
    {
        IAsyncResult result = client.BeginConnect(IPAddress.Parse("192.168.254.34"), 123, null, null);
        success = result.AsyncWaitHandle.WaitOne(3000, true);
    }
    catch (Exception ex)
    {
        success = false;
        MessageBox.Show("error connecting: " + ex.Message + " : " + ex.StackTrace);
    }
}

// NOW, by the time you reach this point, you KNOW that success == true and that you're connected, and you can proceed with the rest of your code

STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;

backgroundWorker1.RunWorkerAsync(); // Começar a receber dados em background
backgroundWorker1.WorkerSupportsCancellation = true; // possibilidade de cancelar o fio

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM