在NetworkStream对象中等待某些信息

本文关键字:信息 等待 NetworkStream 对象 | 更新日期: 2023-09-27 18:15:05

我在过去的几天里一直在尝试使用BeginRead和read方法从NetworkStream对象中读取,但是这两种方法都给我带来了困难,而且似乎不可靠

第一个,"Read"要求我休眠线程,并期望在休眠结束时出现正确的数据。像这样:

cmd = System.Text.Encoding.ASCII.GetBytes(CommandString + "'r");
ns.Write(cmd, 0, cmd.Length);
Thread.Sleep(5000);
int _bytes = ns.Read(output, 0, output.Length);
responseOutput = System.Text.Encoding.ASCII.GetString(output, 0, _bytes);
Console.Write(responseOutput);

这在80%的时间内工作,因为服务器的延迟在一天中波动,我也尝试了下面的方法,我觉得构造很差,什么是最有效的方法来轮询匹配一组不消耗CPU也不浪费时间的条件的数据?

bool connection_check = false;
String[] new_connection_array = new String[] { "processed successfully", "invalid", "Command not recognised. Check validity and spelling" };
do
{
    int view_bytes = ns.Read(output, 0, output.Length);
    responseOutput += System.Text.Encoding.ASCII.GetString(output, 0, view_bytes);
    foreach (String s in new_connection_array)
         if (responseOutput.IndexOf(s) > -1)
             connection_check = true;
} while (connection_check == false);

Thanks in advance

编辑:

 public bool SendCommandAndWait(Byte[] command, Regex condition)
        {
            if (callback == null)
            {
                SendCommand(command);
                callback = ar =>
                {
                    int bytesEnd = ns.EndRead(ar);
                    int bytes = bytesEnd;
                    // Process response
                    responseOutput += System.Text.Encoding.ASCII.GetString(output, 0, bytes);
                    // Check if we can return
                    if (condition.IsMatch(responseOutput))
                        return; // Yes, there is a match... return from the async call
                    else // No match, so loop again
                        ns.BeginRead(output, 0, output.Length, callback, null); // Call the loop again
                };
                ns.BeginRead(output, 0, output.Length, callback, null);
            }
            // Because the callback is fired into a different thread and the program continues, we need to loop here so the program doesn't continue without us
            do
            {
                Thread.Sleep(1000);
                //Console.WriteLine(responseOutput);
            } while (!condition.IsMatch(responseOutput));
            if (condition.IsMatch(responseOutput))
            {
                callback = null;
                return true;
            }
            else
                return false;
        }

在NetworkStream对象中等待某些信息

BeginRead将允许您定义一个在BeginRead结束时执行的操作。注意,这和你读完所有你想读的东西是不一样的。这就是read返回已读字节数的原因。如果您希望读取20个字节而得到10个字节,那么您将需要再读取10个字节。

From https://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread(v=vs.110).aspx:

BeginRead方法读取所有可用的数据,不超过size参数指定的字节数。

如果你想在调用BeginRead方法后阻塞原始线程,请使用WaitOne方法。