c#server-client,客户端没有重新连接

时间:2017-03-24 18:17:22

标签: c# server client

事先感谢任何事情。 我正在制作服务器 - 客户端程序,其中服务器(应用程序)创建服务器并且客户端连接到它,我还将在服务器应用程序上有一个文本框和一个按钮,每当我在该文本框上写入内容并按下按钮,它将发送到客户端应用程序(此应用程序中只有一个文本框,此应用程序唯一做的是从服务器应用程序接收字符串)。

我认为它有效,但不是我想要的方式。 我可以建立连接,也可以从文本框发送和接收信息,但前提是我首先运行服务器应用程序(创建服务器)。问题是,如果我不首先运行服务器应用程序(创建服务器),客户端应用程序将无法连接,甚至尝试。

“错误”示例(我想你可以称之为错误): 如果我先运行客户端应用程序然后再运行服务器应用程序,客户端应用程序就不会连接到服务器应用程序创建的服务器,我做了一个基本上验证客户端是否已连接的循环,如果是,那么它开始接收信息,如果没有(否则)等待3秒并尝试重新连接。但是当它试图重新连接时它不起作用。 有什么想法吗?

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());
            }
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

如果服务器还没有运行,那么由于这条线路的成功总是错误的:

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

由于成功将始终为false,因此永远不会执行while(成功)块内的代码。

将代码重新排列为类似内容可能会有所帮助:

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