首页 > 解决方案 > 统一套接字通信时的错误避免

问题描述

我正在尝试在 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 继续运行而不给出错误消息?

标签: c#socketsunity3d

解决方案


不确定您是否考虑过异常处理。如果您不这样做,这可能会为您指明正确的方向。

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch


推荐阅读