如何在C#中取消/中止TCP IP请求

问题描述

我有Tcp客户端和服务器,我可以与NuGET Package中的SimpleTcp发送请求并获得对方的响应

我可以发送/接收十六进制消息,但是我想询问何时发送请求,我想中止它。

我如何中止请求?

这是我的联系方式

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

    }

使用此功能,我可以发送请求,也可以在按钮单击事件中发送请求

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

解决方法

假设您正在使用此SimpleTcp库,没有什么可以取消their way方法,它正在等待答案或超时。

但是该方法只是预订WriteLineAndGetReply事件,调用DataReceived方法,并使用循环来等待答复或超时结束。

您可以这样做,订阅WriteLine事件,然后等待回复或您自己的取消。

在此处检查https://github.com/BrandonPotter/SimpleTCP/blob/61f1932201a7c5633ad2f003c97c83c31541fc85/SimpleTCP/SimpleTcpClient.cs#L170 有关如何在库中完成代码示例。

向现有方法添加取消令牌的示例:

DataReceived

您将这样使用它:

    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;
    }

有关取消令牌的更多信息:https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=netcore-3.1

,

只需使用TcpClient,您就可以在NetworkStream上调用占用CancellationToken的异步方法。使用CancellationTokenCancellationTokenSource可以取消异步操作。但是我发现的SimpleTcp不要带CanncellationToken。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...