Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I want an event when the disconnect button is pressed or the server closes.
I can't get into the cancellation. Why? What's wrong?
The problem is
I can't get there. Disconnect and abort.
Why not? What's wrong?
try
{
// MyCancellationTokenSource = new CancellationTokenSource();
// while (true) //stream.DataAvailable) //(true)
while (MyCancellationTokenSource.IsCancellationRequested) //stream.DataAvailable) //(true)
{
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, MyCancellationTokenSource.Token);
public class MyTcpClient
{
private TcpClient _client;
CancellationTokenSource MyCancellationTokenSource = new CancellationTokenSource();
public event EventHandler<string> MessageReceived;
/// <summary>
/// Connect to the TCP server
/// </summary>
/// <param name="ipAddress"></param>
/// <param name="port"></param>
public void Connect(string ipAddress, int port)
{
_client = new TcpClient();
_client.Connect(ipAddress, port);
// Start a separate task to receive data
_ = ReceiveDataAsync();
// _ = Task.Run(async () => await ReceiveDataAsync());
}
/// <summary>
/// Send message to the connected server
/// </summary>
/// <param name="message"></param>
public void SendMessage(string message)
{
NetworkStream stream = _client.GetStream();
byte[] buffer = Encoding.ASCII.GetBytes(message);
stream.Write(buffer, 0, buffer.Length);
}
/// <summary>
/// Handle incoming data from the server
/// </summary>
private async Task ReceiveDataAsync()
{
NetworkStream stream = _client.GetStream();
byte[] buffer = new byte[1024];
StringBuilder messageBuilder = new StringBuilder();
try
{
//MyCancellationTokenSource = new CancellationTokenSource();
while (true) //stream.DataAvailable) //(true)
{
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, MyCancellationTokenSource.Token);
if (bytesRead == 0)
{
break; // Server or client disconnected
}
string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
messageBuilder.Append(data);
if (data.Length > 0)
{
string receivedMessage = messageBuilder.ToString();
OnMessageReceived(receivedMessage);
messageBuilder.Clear();
}
}
_client.Close();
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancel XXXX");
}
}
public void Disconnect()
{
MyCancellationTokenSource.Cancel();
_client?.Close();
}
protected virtual void OnMessageReceived(string message)
{
MessageReceived?.Invoke(this, message);
}
}
Thanks for reaching out!
ReadAsync may exit silently without throwing.OnDisconnected() in both places:bytesRead == 0catch (OperationCanceledException)3.Update your loop to handle both cancellation and disconnectionThanks for reaching out!