【发布时间】:2013-06-26 20:21:13
【问题描述】:
所以我正在尝试创建一个使用 TcpClient 从服务器发送和接收数据的系统。我有一个线程正在监听传入的数据。
我想要的是能够制作一个可以:
写入流 > 等待响应 > 处理响应
但与此同时,其他不相关的数据也可能会在这段时间内进来,所以我不能这样做:
writer.WriteLine("");
string response = reader.ReadLine();
我在这个问题中查看“回调”>Callbacks in C#,这似乎是我需要走的路,但我不完全确定如何继续。
任何关于此的帮助都会很棒,谢谢!
为 Jim Mischel 编辑:
这是我想要实现的目标:
public bool Login(string username, string password) {
writer.Write("{ \"username\" : \"" + username + "\", \"password\" : \"" + password + "\" }";
//Somehow get the response which is being ran on another thread (See below)
//Process the JSON into a object and check is successful or not
if (msg.result == "Ok") return true;
else return false;
}
private void ReadThread()
{
while (running)
{
if (ns.DataAvailable)
{
string msg = reader.ReadLine();
if (String.IsNullOrEmpty(msg)) continue;
Process(msg); //Process the message aka get it back to the Login method
}
}
}
编辑 2: 基本上我希望能够调用一个登录方法,该方法将写入一个 TcpClient 并等待接收来自同一流的回复,然后返回一个布尔值。
但是像这样的基本方法并不能解决问题:
public bool Login(string username, string password) {
writer.Write("{ \"username\" : \"" + username + "\", \"password\" : \"" + password + "\" }";
string response = reader.ReadLine();
if (response == "success") return true;
else return false;
}
这不起作用,因为其他数据会通过流自动推送给我,所以在等待 ReadLine() 时,我可能会得到其他任何东西,而不是我正在寻找的响应。
所以我正在寻找一个可以解决这个问题的解决方案,目前我有一个线程正在运行,它纯粹是为了从流中读取然后处理消息,我需要从该线程获取消息到上面方法。
我想到的一种方法是在读取消息时将其放入全局列表中,然后可以将 Login 方法放入一个循环中,该循环检查列表,直到在列表中找到消息。但如果我的想法是正确的,这是一个可怕的概念。所以我正在寻找替代方案。
【问题讨论】:
-
你能保证 C# 5 (.NET 4.5) 吗?
async/await听起来非常适合您的情况,它可以让您继续以同步方式开发代码。 -
希望 .Net 4 是我必须去的最高级别,这将是最后的手段。
-
您也可以通过引用 Microsoft.Bcl.Async Nuget 包并使用 C# 5 编译器来使用 .NET 4。
-
Async/await 可用于 4.0,您只需 download it from NuGet。
-
好的,我如何在上面的例子中加入 async/await?以前从未使用过任何一个关键字!谢谢。
标签: c# multithreading networking tcpclient