如何忽略异常

时间:2016-06-23 18:13:28

标签: c# udp

我使用UDP套接字发送然后接收消息。

因此,当我收到时,我将超时异常设置为4秒......

sending_socket.ReceiveTimeout = 4000;
sending_socket.ReceiveFrom(ByteFromListener, ref receiving_end_point);

现在我得到了这个异常(我期待):System.dll中发生了一个未处理的类型'System.Net.Sockets.SocketException'的异常

其他信息:连接尝试失败,因为连接方在一段时间后没有正确响应,或者由于连接主机无法响应而建立连接失败

我想知道如何忽略此异常?

基本上我希望UDPSOCKET听4秒钟,如果没有回答,那么再尝试发送一条消息..我的代码如下(部分内容)

 IPEndPoint sending_end_point = new IPEndPoint(sendto, sendPort);
        EndPoint receiving_end_point = new IPEndPoint(IPAddress.Any, 0);           

        Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        text_to_send = ("hello");
        byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
        sending_socket.SendTo(send_buffer, sending_end_point);
        Byte[] ByteFromListener = new byte[8000];
        sending_socket.ReceiveTimeout = 4000;
        sending_socket.ReceiveFrom(ByteFromListener, ref receiving_end_point);
        string datafromreceiver;
        datafromreceiver = Encoding.ASCII.GetString(ByteFromListener).TrimEnd('\0');
        datafromreceiver = (datafromreceiver.ToString());

2 个答案:

答案 0 :(得分:6)

try
{
     sending_socket.ReceiveFrom(ByteFromListener, ref receiving_end_point);
}
catch (SocketException ex) { }

答案 1 :(得分:1)

我建议您使用sending_socket.AvailableRead on MSDN)属性,而不是检查例外情况。

您可以添加一个逻辑来检查自发送数据以来经过的时间,然后如果“可用”尚未成立,请尝试再次发送。如下所示:

bool data_received = false;
do
{
    DateTime dtSent;
    sending_socket.SendTo(send_buffer, sending_end_point);
    dtSent = DateTime.Now;

    while(DateTime.Now - dtSent < TimeSpan.FromSeconds(4))
    {
       while(sending_socket.Available)
       {
          int bytes_available = sending_socket.Available;
          // you can use bytes_available variable to create a buffer of the required size only.
          //read data... and concatenate with previously received data, if required
          data_received = true;  
       }
       Thread.Sleep(100); // sleep for some time to let the data arrive
    }
}while(!data_received);

上面的代码只是一个简单的示例逻辑。请根据您的要求进行修改。

我强烈建议您不要依赖异常来处理您可能已经知道的案例。例外情况是为了处理事先无法知道且无法检查机制的案件。

此外,由于其他原因可能会引发SocketException,例如Endpoint不可用,连接因任何原因而丢失。应该针对这些场景处理异常,以便您的代码可以正确处理这些场景。