问题描述
我有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的异步方法。使用CancellationToken和CancellationTokenSource可以取消异步操作。但是我发现的SimpleTcp不要带CanncellationToken。