Exception Handling

Exception Handling

By now you are probably wondering how to handle socket errors. In traditional Winsock, handling errors requires checking the return code of every Winsock call that is made in your application. In .NET Sockets using C#, this is not quite true. C# is designed to handle errors through exception handling in which you can wrap one or more .NET Sockets calls in a try-catch block of code. Most of the .NET Sockets calls raise a System.Net.Sockets.SocketException when a socket error occurs. When the exception is raised, your catch block can receive System.Net.Sockets.SocketException object. The SocketException object has two important properties: ErrorCode and Message. The ErrorCode property contains the actual Winsock error code that occurred on the socket. The Message property is an error message related to the Winsock error code. The following code fragment demonstrates how to handle a SocketException error from the Receive method.

try { MySocket.Receive(Buffer); } catch (SocketException err) { Console.WriteLine("The Winsock error code is " + err.ErrorCode); Console.WriteLine("The related error message is " + err.Message); }

Another exception worth mentioning is that you can also receive a System. ObjectDisposedException if your application closes a socket and you continue to perform methods in the Socket class, such as receiving data on a socket. This can happen when you post several asynchronous calls, such as BeginReceive, and you close your socket for whatever reason. When your outstanding BeginReceive calls complete because of socket closure, they typically call EndReceive to retrieve results. Because the socket is closed, EndReceive will raise an ObjectDisposedException exception.

There are more exceptions that can be handled on each of the .NET Sockets methods. We highly recommend reviewing the .NET Application Frameworks SDK for more information.



Network Programming for Microsoft Windows
Network Programming for Microsoft Windows (Microsoft Professional Series)
ISBN: 0735605602
EAN: 2147483647
Year: 2001
Pages: 172
Authors: Anthony Jones

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