321237 HOWTO: Wayed a non-fatal Winsock error in Visual Studio .NET (from mkba)

xiaoxiao2021-03-06  78

summary

SocketException has two types: fatal exceptions and non-fatal exceptions.

In the Microsoft C # program or the Microsoft Visual Basic .NET program, there is usually a TRY block, a Catch block, and a FinalLy block. When an exception is obtained in the TRY block, the exception will be captured in the CATCH block. If you are a fatal error, you can make some cleaning work in the FinalLip before exiting the application.

However, sometimes it encounters related to socket, non-fatal exceptions, such as

Connection Refused (Connection Rejected) and

Receive Timed-Out (receiving timeout). You can handle these exceptions moderately and continue the application.

The following client illustrates the connection three times and moderately processes the WSAEConnRefused (10061) error.

The Connect statement has a separate TRY-CATCH block.

All socket exceptions caused by the Connect statement will be captured 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.RecEcept (Resbuffer);

Console.Writeline ("Received Data from Server:" asciiencoding.ascii.getstring (resbuffer); ClientSock.shutdown (socketshutdown.both);

}

Clientsock.close ();

}

Catch (Exception E)

{

Console.writeline (E.TOString ());

}

}

}

The information in this article applies to:

Microsoft Visual Studio .NET (2002), Professional Edition

Recent Updated: 2003-8-6 (1.0) Keyword kbhowto KB321237

转载请注明原文地址:https://www.9cbs.com/read-108905.html

New Post(0)