Microsoft KB Archive/321237

= How To Gracefully Handle Nonfatal WinSock Errors in Visual Studio .NET =

Article ID: 321237

Article Last Modified on 10/11/2004

-

APPLIES TO


 * Microsoft Visual Studio .NET 2002 Professional Edition

-



This article was previously published under Q321237



SUMMARY
There are two types of SocketExceptions: fatal exceptions and nonfatal exceptions.

In a Microsoft C# program or in a Microsoft Visual Basic .NET program, you typically have a try block, a catch block, and a finally block. When you get an exception in the try block, it is caught in the catch block. When the error is fatal, you can do some clean-up in the finally block before you quit the application.

But sometimes you have nonfatal, socket-related exceptions such as Connection Refused and Receive Timed-Out. You can handle these exceptions gracefully and then continue in the application.

The following client sample retries the connection three times and handles the WSAECONNREFUSED (10061) error gracefully. The Connect statement has a separate try-catch block. Any Socket exception that the Connect statement throws is caught in the corresponding catch block.



MORE INFORMATION
using System; using System.Net.Sockets; using System.Net; using System.Text;

class App {

[STAThread] static void Main(string[] args) {       string msg = &quot;Hello server&quot;; Byte[] buffer = ASCIIEncoding.ASCII.GetBytes(msg); Byte[] resBuffer = new Byte[500]; int retry = 1, bytes; bool runApp = true; try {           Console.Write(&quot;Enter the Server you would like to connect: &quot;); String serverName = Console.ReadLine;

IPAddress ip = Dns.Resolve(serverName).AddressList[0]; Console.Write(&quot;Enter the Port: &quot;); int Port = Int32.Parse(Console.ReadLine);

IPEndPoint serverEP = new IPEndPoint(ip,Port); Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

while (retry <= 3) {               try {                   clientSock.Connect(serverEP); }               catch (SocketException e)                { if (e.ErrorCode == 10061) {                       Console.WriteLine(&quot;Connect error. Trying to connect again......&quot;); retry++; runApp = false; }                   else {                          runApp = true; break; }               }            }

if (runApp) {               clientSock.Send(buffer,buffer.Length,0); bytes = clientSock.Receive(resBuffer); Console.WriteLine(&quot;Received Data from Server : &quot; + ASCIIEncoding.ASCII.GetString(resBuffer)); clientSock.Shutdown(SocketShutdown.Both); }           clientSock.Close; }       catch (Exception e)        { Console.WriteLine(e.ToString); }   }   }

Keywords: kbhowto kbdswnet2003swept KB321237

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.