c# - 统一套接字通信时的错误避免
问题描述
我正在尝试在 Unity 上接收与 C# 的套接字通信。
如果 Send.py 被中断,下面的 unityRecieve.cs 将导致错误。
发送.py
import socket
import random
HOST = '127.0.0.1'
PORT = 50007
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
a = random.randrange(3)
result = str(a)
print(a)
client.sendto(result.encode('utf-8'),(HOST,PORT))
time.sleep(2.0)
unityRecieve.cs
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class unityRecieve : MonoBehaviour
{
static UdpClient udp;
void Start()
{
int LOCA_LPORT = 50007;
udp = new UdpClient(LOCA_LPORT);
udp.Client.ReceiveTimeout = 100;
}
void Update()
{
IPEndPoint remoteEP = null;
byte[] data = udp.Receive(ref remoteEP);
string text = Encoding.UTF8.GetString(data);
Debug.Log(text);
}
}
https://jump1268.hatenablog.com/entry/2018/11/25/143459
当 Send.py 中断时,如何使 unitiRecieve.cs 继续运行而不给出错误消息?
解决方案
不确定您是否考虑过异常处理。如果您不这样做,这可能会为您指明正确的方向。
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch
推荐阅读
- c++ - 在支持多种类型的宏中使用 printf
- c++ - Glade Gui 问题
- java - 如何检查 Enum 是否在 Java 中使用
- vue.js - 如何在 vue 中创建/更新羽毛笔印迹?
- java - 如何检查firebase数据库中2个随机键中的值?
- graphql - Gatsby 在获取 graphql 时在构建期间给出错误“错误:名称为“文件”的类型不存在”
- symfony - 如何使用 Symfony 4 从 Web URL 生成 pdf?
- rust - 不能使用 format_args!由于临时值在此语句的末尾被释放
- java - 为什么我在这里使用方法引用或 lambda 很重要?
- mysql - `utf8_general_ci' 是弃用字符集 UTF8MB3 的排序规则