当我尝试在RecData()方法中接收数据时,为什么我的udp客户端没有抛出异常?

时间:2019-05-19 01:00:44

标签: c# .net udp

它用于多人视频游戏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace ShootingMasters
{
    public class Communicator
    {
        public UdpClient client;
        public IPAddress toconnectto;

        public Communicator(IPAddress toconnectto)
        {
            this.toconnectto = toconnectto;
            client = new UdpClient();
            client.Connect(toconnectto, 25565);
        }

        public void SendData(string data)
        {
            byte[] bdata = ASCIIEncoding.ASCII.GetBytes(data);
            IPEndPoint iP = new IPEndPoint(toconnectto, 25565);

            try
            {
                client.Send(bdata, bdata.Length);
            }
            catch(Exception e)
            {
            }
        }

        public string RecData()
        {
            if (client.Available > 0)
            {
                try
                {
                    IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 25565);
                    byte[] data = client.Receive(ref iPEndPoint);
                    return ASCIIEncoding.ASCII.GetString(data);
                }
                catch(Exception e)
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
    }
}

当您调用receive时,由于引发了异常,它返回null。异常消息是

  

远程主机强行关闭了现有连接

此外,在接收客户端内部。可用值为1,然后在引发异常后立即为0。

0 个答案:

没有答案