saulyasar
saulyasar

Reputation: 815

How to cancel/abort TCP IP Request in C#

I have Tcp client and Server i can send request and get response each other with SimpleTcp from NuGET Package

I can send/receive Hexadecimal messages but I want to ask when i send request i want to abort it.

How can i abort request?

Here how i connect

    SimpleTcpClient client;
    private void Form1_Load(object sender, EventArgs e)
    {
        client = new SimpleTcpClient();
        client.StringEncoder = Encoding.UTF8;
        client.DataReceived += Client_DataReceived;

    }

With this function i'm sending request and i'm sending it on button click event

    private void btnStart_Click(object sender, EventArgs e)
    {
        //do something
        client.WriteLineAndGetReply(request, TimeSpan.FromSeconds(1));
    }

Upvotes: 0

Views: 874

Answers (2)

Gimly
Gimly

Reputation: 6175

Assuming you're using this SimpleTcp library, there is nothing to cancel the WriteLineAndGetReply method, it's waiting for either an answer or the timeout.

But the method is just subscribing to the DataReceived event, calling the WriteLine method, and using a loop to wait for a reply or the end of the timeout.

You can do the same, subscribe to the DataReceived event and wait for a reply or your own cancellation.

Check here https://github.com/BrandonPotter/SimpleTCP/blob/61f1932201a7c5633ad2f003c97c83c31541fc85/SimpleTCP/SimpleTcpClient.cs#L170 For the code sample on how it's done in the library.

Example adding a cancellation token to the existing method:

    public Message WriteLineAndGetReplyWithCancel(
        string data, 
        TimeSpan timeout, 
        CancellationToken cancellationToken = default)
    {
        Message mReply = null;
        this.DataReceived += (s, e) => { mReply = e; };
        WriteLine(data);

        Stopwatch sw = new Stopwatch();
        sw.Start();

        while (mReply == null && 
               sw.Elapsed < timeout &&
               !cancellationToken.IsCancellationRequested)
        {
            System.Threading.Thread.Sleep(10);
        }

        return mReply;
    }

You would use it like that:

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;

WriteLineAndGetReplyWithCancel(request, TimeSpan.FromSeconds(1), token);

// To cancel
source.Cancel();

More information about cancellation token: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=netcore-3.1

Upvotes: 2

Vabka
Vabka

Reputation: 101

With bare TcpClient you can call asynchronous methods on NetworkStream which take CancellationToken. With CancellationToken and CancellationTokenSource you can cancel asynchronous operation. But SimpleTcp which i found, don't take CanncellationToken.

Upvotes: 0

Related Questions