【发布时间】:2021-06-07 16:52:19
【问题描述】:
我在多人项目中有一个 try-catch 语句,用于检查 Unity 中的连接状态(通过 UDP)。它在 try 代码块中接收来自服务器的回调,而 catch 代码块用于在连接突然中断的情况下获取异常。我的问题是 catch 块没有执行我用来通知用户与服务器的连接已丢失的代码。它似乎只执行与异常相关的代码(如 Debug.Error(e))。
//Callback from server connection
private void ConnectCallback(IAsyncResult _result) {
try {
//Ends connection
socket.EndConnect(_result);
} catch (Exception e) {
//These three lines are the problem. They won't execute
UIManager.instance.logPanel.enabled = true;
UIManager.instance.logPanel.text = "Servidor no disponible";
UIManager.instance.HideUsernameSelection();
}
//If theres no connection to the server the function returns
if (!socket.Connected)
{
return;
}
//Reference to data stream
stream = socket.GetStream();
//Packet for data received from server
receivedData = new Packet();
//Read
stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
}
有没有强制catch块执行里面的代码?
【问题讨论】:
-
socket.EndConnect 似乎正在结束连接(根据代码和 MS 文档中的 cmets)。我在 try 中没有看到任何 connect 方法,那么您为什么期望捕获错误?
-
对不起,我没有复制整个函数。我刚刚更新了它。如果连接到服务器的回调为负,我想要的是从 UIManager 执行函数,这样我就可以显示重新连接 UI 和服务器错误。
标签: c# visual-studio unity3d