如何从网络流中读取安全保护?

时间:2018-02-19 14:28:31

标签: c#

目前我正在开发一个可以在网络上运行的小项目。我编写了一个读取和写入流的网络管理器。但是当我尝试加入我的阅读主题时,我遇到了问题。当我调用thread.join方法时,线程开始挂起。这是我的代码:

private TcpClient playerClient;
private NetworkStream playerStream;
private Thread readThread;
private bool isReading;

public void Read()
{
    while (this.isReading == true)
    {
        try
        {
            if (!this.playerStream.DataAvailable)
            {
                Thread.Sleep(10);
                continue;
            }

            List<byte> receivedBytes = new List<byte>();
            byte[] buffer = new byte[1];
            int currentByte = 0;

            while (this.playerStream.DataAvailable)
            {
                currentByte = this.playerStream.Read(buffer, 0, 1);
                receivedBytes.Add(buffer[0]);
            }

            this.FireOnDataReceived(receivedBytes.ToArray());
        }
        catch
        {
            this.FireOnConnectionLost();
        }
    }
}

public void Stop()
{
    try
    {
        this.isReading = false;
        this.playerStream.Close();
        this.playerClient.Close();
        this.readThread.Join();
    }
    catch
    {

    }
}

public void Start()
{
    try
    {
        this.playerStream = this.playerClient.GetStream();
        this.readThread = new Thread(this.Read);
        this.isReading = true;
        readThread.Start();
    }
    catch
    {
        this.FireOnConnectionLost();
    }
}

0 个答案:

没有答案