[英]c# server-client, client doesnt reconnect
預先感謝任何事情。 我正在制作一個服務器-客戶端程序,其中服務器(應用程序)創建一個服務器,客戶端連接到該服務器,我還將在服務器應用程序上有一個文本框和一個按鈕,並且每當我在該文本框上寫一些東西並按下按鈕時,它將發送到客戶端應用程序(此應用程序中只有一個文本框,此應用程序唯一要做的就是從服務器應用程序接收字符串)。
我認為它有效,但不是我想要的方式。 我可以建立連接,也可以從文本框中發送和接收信息,但前提是我必須先運行服務器應用程序(以創建服務器)。 問題是,如果我不首先運行服務器應用程序(以創建服務器),則客戶端應用程序將無法連接,甚至無法連接。
“錯誤”的示例(我想您可以稱其為錯誤):如果先運行客戶端應用程序,然后再運行服務器應用程序,則客戶端應用程序將無法連接至該服務器應用程序創建的服務器,因此發生了循環基本上驗證客戶端是否被連接,如果是,則它開始接收信息,否則,則等待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());
}
}
}
}
}
如果服務器尚未運行,則由於以下原因,成功總是錯誤的:
bool success = result.AsyncWaitHandle.WaitOne(3000, true);
由於成功總是錯誤的,因此while(success)塊中的代碼將永遠不會執行。
將代碼重新排列為類似以下內容可能會有所幫助:
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.