简体   繁体   English

为什么用networkstream.write块?

[英]Why networkstream.write block?

I have client server project. 我有客户端服务器项目。 i have a problem in sending data from server to clients. 我在从服务器向客户端发送数据时遇到问题。

    private bool SendPack(object client, string data)
    {
        lock (this)
        {
            try
            {
                NetworkStream clientStream = tcpServer.GetStream();

                byte[] Pack= ClsEncryption.GetEncrypt(data);

                clientStream.Write(Pack, 0, Pack.Length);
                clientStream.Flush();

                return true;
            }

            catch
            {                    
                return false;
            }
        }
    }

although i use lock, when write command runs, everything ruin. 虽然我使用锁,但是当运行写命令时,一切都崩溃了。 i mean nothing send and the write does not return(like blocking). 我的意思是什么也没有发送,并且写操作也不会返回(如阻塞)。 should i use asynch methods by using beginwrite or not? 是否应该通过使用beginwrite来使用异步方法? how can i check if the networkstream is ready to write and would not block. 我如何检查networkstream是否已准备好写入并且不会阻塞。 i use clientstream.canwrite, but it was not useful. 我使用clientstream.canwrite,但没有用。

I need the fastest and most reliable way to send data. 我需要最快,最可靠的方式发送数据。 Any Idea? 任何想法?

If there are simultaneous read operations with this stream on other thread, and if read operations uses lock on same instance, threads will possably deadlock. 如果与此流同时在其他线程上进行读取操作,并且读取操作在同一实例上使用锁,则线程可能会死锁。 If that is true, use different instances for locking read and write operations or send | 如果是这样,请使用其他实例锁定读取和写入操作或发送| read data outside the lock statement. 在lock语句之外读取数据。

According to the documentation you can use the CanWrite property: 根据文档,您可以使用CanWrite属性:

if (clientStream.CanWrite)
{
    clientStream.Write(Pack, 0, Pack.Length);
    clientStream.Flush();
    return true;
}

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

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