c# - 如何忽略异常

标签 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());

最佳答案

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

关于c# - 如何忽略异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37998950/

相关文章:

具有多个接口(interface)的 Python UDP 套接字

udp - 如何使用netcat只发送一个UDP数据包?

c# - 如何生成动态for循环

c# - 线程、事件和 GUI

c# - 使用 openXML 创建模板演示文稿 ".potx"的副本到新的 ".pptx"

c# - 选择具有特定值的节点

c# - 如何在 visual studio 2013 中设置 "Target Framework"?

c# - .NET 应用程序需要微秒级延迟来限制 UDP 多播传输速率

sockets - Dart UDP 客户端/服务器

linux - 使用scapy高频发送UDP ping,为什么只收到前几个ICMP端口不可达报文?