现在的位置: 首页 > 综合 > 正文

321237 HOWTO:在 Visual Studio .NET 中适度地处理非致命 WinSock 错误 (From MKBA)

2013年11月21日 ⁄ 综合 ⁄ 共 1571字 ⁄ 字号 评论关闭
文章目录

概要

SocketExceptions 有两种类型:致命异常和非致命异常。

在 Microsoft C# 程序或 Microsoft Visual Basic .NET 程序中,通常有 try 块、catch 块和 finally 块。当在 try 块中获得异常时,将在 catch 块中捕获该异常。如果是致命错误,在退出应用程序之前,可以在 finally 块中进行一些清理工作。

但是,有时会遇到与套接字相关的、非致命的异常,如 Connection Refused(连接被拒绝)和 Receive Timed-Out(接收超时)。您可以适度地处理这些异常,然后继续执行应用程序。

下面的客户端示例重试连接三次,并适度地处理 WSAECONNREFUSED (10061) 错误。Connect 语句有一个单独的 try-catch 块。Connect 语句引发的所有 Socket 异常都将在相应的 catch 块中捕获。

更多信息

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());
		}
	}	
}
				

这篇文章中的信息适用于:

  • Microsoft Visual Studio .NET (2002), Professional Edition
最近更新: 2003-8-6 (1.0)
关键字 kbhowto KB321237

抱歉!评论已关闭.