2017-03-24 43 views
0

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

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

“错误”(我想你可以把它叫做一个错误)的例子: 如果我运行的客户端应用程序,然后再在服务器应用程序,客户端应用程序只是将无法连接到服务器应用程序创建的服务器,我做了一个循环,基本验证客户端是否连接,如果是,则开始接收信息,否则等待3秒钟并尝试再次重新连接。但是当它试图重新连接它不起作用。 任何想法?

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

}

+0

通过我放在问题的代码是从客户端应用程序 –

+0

服务器具有监听客户端可以连接前的样子。您无法首先启动客户端,否则您会收到错误消息。这是TCP工作的方式。 – jdweng

+0

所以你说的是,我不能让客户端先走,让他等到服务器运行?......因为这是我假装要做的事情......让客户端去首先使他搜索服务器应用程序创建的服务器,直到服务器没有创建,客户端应该继续搜索直到它被创建...是不可能的? –

回答

0

如果服务器尚未运行,那么成功总是会是假的,因为这行的结果:

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

由于成功永远是错误的,你的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 
+0

它是否适合你?,因为我试着按照你说的方式,我仍然没有得到结果即时寻找:/ –