开发者

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? how can i check if the networkstrea开发者_运维百科m is ready to write and would not block. i use clientstream.canwrite, but it was not useful.

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.


According to the documentation you can use the CanWrite property:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜