问题:下方函数启动了一个UDP监听,在接收到某udp信息时会发生报错
SocketException: Connection reset by peerat System.Net.Sockets.Socket.ReceiveFrom (System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint& remoteEP) [0x0003e] in <d8cd0ec6fc774382b0a4c707a194e94c>:0 at System.Net.Sockets.Socket.ReceiveFrom (System.Byte[] buffer, System.Net.EndPoint& remoteEP) [0x00000] in <d8cd0ec6fc774382b0a4c707a194e94c>:0 at Main.OpenUdp () [0x0007e] in <231fb2ff133c441aa6c918576743bbd4>:0 at System.Threading.ThreadHelper.ThreadStart_Context (System.Object state) [0x00014] in <c044b30621b545ab8aaed051a9ff936b>:0 at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00071] in <c044b30621b545ab8aaed051a9ff936b>:0
由于对方断开连接导致异常???
问题代码如下
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Xml;
using UnityEngine;
using UnityEngine.UI;// Token: 0x02000002 RID: 2
public partial class Main : MonoBehaviour
{// Token: 0x06000010 RID: 16 RVA: 0x00002EFC File Offset: 0x000010FCprivate void OpenUdp(){XmlElement xmlElement = (XmlElement)this.doc.SelectSingleNode("admin");this.xmlip = xmlElement.GetAttribute("ip");int port = int.Parse(xmlElement.GetAttribute("port"));this.serverPort = port;Debug.Log("启动udp监听,xmlip"+xmlip+"port:"+port);IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(this.xmlip), port);Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(localEP);EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);for (;;){byte[] array = new byte[1024];int count = socket.ReceiveFrom(array, ref remoteEP);string str = string.Format(Encoding.Default.GetString(array, 0, count), Array.Empty<object>());socket.SendTo(Encoding.Default.GetBytes("Successfully!"), remoteEP);if (this.flag){this.flag = false;this.uiStr = str;socket.SendTo(Encoding.Default.GetBytes("code=" + str), remoteEP);Debug.Log("收到消息:" + str);}}}
}
修改函数如下,发生异常时结束并重新启动udp监听
可以解决断线造成的异常问题
private void OpenUdp()
{XmlElement xmlElement = (XmlElement)this.doc.SelectSingleNode("admin");this.xmlip = xmlElement.GetAttribute("ip");int port = int.Parse(xmlElement.GetAttribute("port"));this.serverPort = port;IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(this.xmlip), port);// 创建 UDP 套接字Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);socket.Bind(localEP);EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);try{while (true){byte[] array = new byte[1024];try{// 接收数据int count = socket.ReceiveFrom(array, ref remoteEP);string str = Encoding.Default.GetString(array, 0, count);// 响应数据socket.SendTo(Encoding.Default.GetBytes("Successfully!"), remoteEP);if (this.flag){this.flag = false;this.uiStr = str;socket.SendTo(Encoding.Default.GetBytes("code=" + str), remoteEP);Debug.Log("收到消息:" + str);}}catch (SocketException ex){// 捕获并处理连接重置的异常if (ex.SocketErrorCode == SocketError.ConnectionReset){Debug.LogWarning("连接被远程主机重置,准备重试...");// 可以选择重试或继续等待新的数据continue; // 跳过当前循环,继续等待接收新数据}else{// 其他 Socket 异常Debug.LogError("SocketException: " + ex.Message);break; // 如果出现不可恢复的异常,跳出循环}}catch (Exception ex){// 捕获其他异常Debug.LogError("Exception: " + ex.Message);break; // 如果出现其他错误,也跳出循环}}}catch (Exception ex){Debug.LogError("Error initializing UDP socket: " + ex.Message);}finally{// 确保关闭 socketif (socket != null && socket.Connected){socket.Close();}}
}
//问:发送端如何发送才能避免结束连接导致的接收端异常