I have function i use for send message to server. The server return string like 'true' or 'false' and the client return the value returned by the server. My problem is when i call ClientReturn with my request i got my return in the function but not into another function string or if(ClientReturn() == "false / true") it's empty
public static string ClientReturn(string ip, int port, string message)
{
string toReturn = "";
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork = delegate (object s, DoWorkEventArgs args)
{
//---data to send to the server---
string textToSend = message;
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(ip, port);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
toReturn = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
Console.WriteLine("Returned: " toReturn); //It's the return of the server
client.Close();
};
worker.RunWorkerAsync();
return toReturn; //Return the value but not work it's return nothing
}
CodePudding user response:
The problem is that you are not waiting for the BackgroundWorker
to complete.
To be honest, BackgroundWorker
is obsolete anyway. Instead use async
and await
.
You are also missing using
blocks to dispose the client and stream.
public static string ClientReturn(string ip, int port, string textToSend)
{
//---create a TCPClient object at the IP and port no.---
using (TcpClient client = new TcpClient())
{
await client.ConnectAsync(ip, port);
using (NetworkStream nwStream = client.GetStream())
{
byte[] bytesToSend = Encoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " textToSend);
await nwStream.WriteAsync(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = await nwStream.ReadAsync(bytesToRead, 0, client.ReceiveBufferSize);
var toReturn = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
Console.WriteLine("Returned: " toReturn); //It's the return of the server
return toReturn; //Return the value but not work it's return nothing
};
}
}