How To Gracefully Handle Nonfatal WinSock Errors in Visual Studio .NET (321237)



The information in this article 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 = "Hello server";
		Byte[] buffer = ASCIIEncoding.ASCII.GetBytes(msg);
		Byte[] resBuffer = new Byte[500];
		int retry = 1, bytes;			
		bool runApp = true;
		try
		{
			
			Console.Write("Enter the Server you would like to connect: ");
			String serverName = Console.ReadLine();

			IPAddress ip = Dns.Resolve(serverName).AddressList[0];
			Console.Write("Enter the Port: ");
			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("Connect error. Trying to connect again......");
						retry++;
						runApp = false;
					}
					else
					{	
						runApp = true;
						break;
					}
				}
			}

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

Modification Type:MinorLast Reviewed:10/11/2004
Keywords:kbDSWNET2003Swept kbhowto KB321237