When to use TcpClient.ReceiveTimeout and NetworkStream.ReadTimeout?

When programming a TCP server, I would like to set a timeout period for reading a request from a client:

var tcpClient = tcpListener.AcceptTcpClient(); var networkStream = tcpListener.GetStream(); tcpClient.ReceiveTimeout = 10000; networkStream.ReadTimeout = 10000; 

See the last two lines. Which one should I prefer? Are they equal in terms of efficiency or how do they differ?

+6
source share
1 answer

Which one should I prefer?

Both the former and the latter will set their internal Socket to the received timeout. The same socket will bubble from the created TcpClient into NetworkStream , so I would go with the first one.

Are they equal in terms of efficiency or how do they differ?

Good thing we can see the source code . This is TcpClient.ReceiveTimeout :

 public int ReceiveTimeout { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); } } 

Which sets the timeout for receiving an underling client socket ( Client is of type Socket ). Then the NetworkStream is passed:

 public NetworkStream GetStream() { // Shortened for brevity if (m_DataStream==null) { m_DataStream = new NetworkStream(Client, true); } return m_DataStream; } 

And when NetworkStream looks for a timeout, it looks inside Socket :

 public override int ReadTimeout { get { int timeout = (int)m_StreamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); if (timeout == 0) { return -1; } } return timeout; } 
+5
source

Source: https://habr.com/ru/post/987720/


All Articles