2017-03-24 297 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

它是否適合你?,因爲我試着按照你說的方式,我仍然沒有得到結果即時尋找:/ –