11.10 Set Socket Options


Problem

You need to set low-level socket options, such as those that specify send and receive timeouts.

Solution

Use the Socket.SetSocketOption method. You can set the properties of the socket that is used to listen for requests or those of the socket used for a specific client session.

Discussion

You can use the Socket.SetSocketOption method to set a number of low-level socket properties. When calling this method, you supply the following three parameters:

  • A value from the SocketOptionLevel enumeration, which indicates the type of socket that the setting applies to (for example, TCP, UDP, and so on).

  • A value from the SocketOptionName enumeration, which specifies the actual socket setting you are changing. Refer to the .NET Framework documentation for a full list of socket SocketOptionName values.

  • A value that represents the new setting. This is usually an integer, but it can also be a byte array or an object type.

Here's an example that sets the send timeout of a socket:

 // Send operations will time out if confirmation is not received within 1000 // milliseconds. socket.SetSocketOption(SocketOptionLevel.Socket,   SocketOptionName.SendTimeout, 1000); 

Notice that in order to access the socket that represents a client/server connection, you must use the TcpListener.AcceptSocket method instead of TcpListener.AcceptTcpClient , as discussed in recipe 11.9.

You can also set the socket options for the socket that is used by the TcpListener to monitor for connection requests. However, you must take a few additional steps. The TcpListener provides a Socket property, but its accessibility is protected , which means you can't access it directly. Instead, you must derive a new class from TcpListener , as shown on the following page.

 public class CustomTcpListener : TcpListener {     public Socket Socket {         get {return base.Server;}     }     public CustomTcpListener(IPAddress ip, int port) : base(ip, port) {} } 

You can now use this class when creating a TcpListener . Here's an example that uses this approach to set a socket option:

 CustomTcpListener listener = new CustomTcpListener(IPAddress.Parse(     "127.0.0.1"), 8000); listener.Socket.SetSocketOption(SocketOptionLevel.Socket,   SocketOptionName.ReceiveTimeout, 1000); // (Now use CustomTcpListener in the same way you would use TcpListener.) 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net