繁体   English   中英

如何在C#中暂停接收数据流(TCP协议)?

[英]How to pause receiving stream of data (TCP protocol) in C#?

有谁能告诉我如何在我的代码中暂停接收数据流? 目前,我的脚本(如下所示)能够:-等待数据-数据从第三方软件流式传输后立即读取数据(TCP协议)

->我一直坚持如何实现代码以在我收到一个字符(例如我的字符为“ a”或“ b”)后暂停数据流。 我听说通过这种协议的实现,我还是很陌生。

我的最终目标是创建一个循环,其中第三方软件使用TCP协议向UNITY发送“ a”或“ b”,然后UNITY接收“ a”或“ b”,并基于此更新对象的颜色字符。

谢谢你的帮助,

亚尼克

// Initialization of the script 
void Start() 
{ 
    _renderer = GetComponent(); 
    listener = new TcpListener(55001); 
    listener.Start(); 
    print("is listening"); 
}

void Update()
{
    if (!listener.Pending())
    { }
    else
    {
        print("socket comes");
        TcpClient client = listener.AcceptTcpClient();
        NetworkStream ns = client.GetStream();
        StreamReader reader = new StreamReader(ns);
        coherence = reader.ReadToEnd();
        print(coherence);
    }

    if (coherence == "a")
    {
        colorFin = Color.green;
    }
    else if (coherence == "b")
    {
        colorFin = Color.yellow;
    }
}

我还没有尝试过,但是我认为这样应该可以:

...
else
{
    print("socket comes");
    TcpClient client = listener.AcceptTcpClient();
    NetworkStream ns = client.GetStream();
    StreamReader reader = new StreamReader(ns);
    while (true)
    {
        char coherence = (char)reader.Read());
        print(coherence);

        //... handle colors and whatever you want...
    }

}

因为StreamReader.Read一次读取一个字符。

您可能希望某些逻辑在“任务”或“线程”中执行工作,并处理不正确的接收数据。 我认为,但这超出了这个问题的范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM