【问题标题】:ERROR: NullReferenceException: Object reference not set to an instance of an object错误:NullReferenceException:对象引用未设置为对象的实例
【发布时间】:2019-08-18 01:02:33
【问题描述】:

我正在尝试创建 TCP 客户端-服务器连接,客户端可以成功连接到服务器,但我无法接收从服务器发送的数据,并且出现此错误:

NullReferenceException:对象引用未设置为对象的实例 ClientHandlePackets.HandleDataPackets (System.Byte[] data) (at Assets/Client/Scripts/ClientHanlePackets.cs:89) ClientHandlePackets.HandleData (System.Byte[] data ) (在 Assets/Client/Scripts/ClientHanlePackets.cs:61) ClientTCP.Update () (在 Assets/Client/Scripts/ClientTCP.cs:31)

我该如何解决这个问题?

c#
using System.Collections.Generic;
using UnityEngine;

public enum ServerPackets
{
    S_INFORMATION = 1,
    S_EXECUTEMETHODONCLIENT,
}

public class ClientHandlePackets : MonoBehaviour
{

    public static Bytebuffer playerbuffer;
    public delegate void Packet_(byte[] data);
    private static Dictionary<long, Packet_> packets;
    private static long pLength;

    private void Awake()
    {
        initalizePackets();
    }

    private static void initalizePackets()
    {
        packets = new Dictionary<long, Packet_>();
        packets.Add((long)ServerPackets.S_INFORMATION, PacketInformation);
    }

    public static void HandleData(byte[] data)
    {
        byte[] Buffer;
        Buffer = (byte[])data.Clone();

        if (playerbuffer == null) { playerbuffer = new Bytebuffer(); };
        playerbuffer.WriteBytes(Buffer);

        if (playerbuffer.Count() == 0)
        {
            playerbuffer.Clear();
            return;
        }

        if (playerbuffer.Length() >= 8)
        {
            pLength = playerbuffer.ReadLong(false);
            if (pLength <= 0)
            {
                playerbuffer.Clear();
                return;
            }
        }

        while (pLength > 0 & pLength <= playerbuffer.Length() - 8)
        {
            if (pLength <= playerbuffer.Length() - 8)
            {
                playerbuffer.ReadLong(); //REads out the packet identifier
                data = playerbuffer.Readbytes((int)pLength); // Gets the full package length
                HandleDataPackets(data);
            }
            pLength = 0;
            if (playerbuffer.Length() >= 8)
            {
                pLength = playerbuffer.ReadLong(false);

                if (pLength < 0)
                {
                    playerbuffer.Clear();
                    return;
                }
            }

        }

    }
    private static void HandleDataPackets(byte[] data)
    {
        long packetIdentifier;
        Bytebuffer Buffer;
        Packet_ packet;

        Buffer = new Bytebuffer();
        Buffer.WriteBytes(data);
        packetIdentifier = Buffer.ReadLong();
        Buffer.Dispose();

        if (packets.TryGetValue(packetIdentifier, out packet))
        {
            packet.Invoke(data);
        }
    }

    private static void PacketInformation(byte[] data)
    {
        Bytebuffer buffer = new Bytebuffer();
        buffer.WriteBytes(data);

        long packetIdentifier = buffer.ReadLong();
        string msg1 = buffer.Readstring();
        string msg2 = buffer.Readstring();
        int Level = buffer.ReadInteger();


        Debug.Log(msg1);
        Debug.Log(msg2);
        Debug.Log(Level);

    }

}
    using System;
    using System.Net.Sockets;
    using UnityEngine;
    using UnityEngine.UI;

    public class ClientTCP: MonoBehaviour
    {
        public Text info;
        public static ClientTCP instance;
        public TcpClient client;
        public NetworkStream mystream;
        private byte[] AsynchBuffer;
        public bool IsConnected;

        public byte[] Receivebyte;
        public bool handleData = false;



        private string IP_Adress= "127.0.0.1";
        private int port=5555;
        private void Awake()
        {
            instance = this;
        }

        private void Update()
        {
            if (handleData == true)
            {
                ClientHandlePackets.HandleData(Receivebyte);
                handleData = false;
            }
        }

        public void Connect()
        {
            Debug.Log("Trying to connect to the sever...");
            client = new TcpClient();
            client.ReceiveBufferSize = 4096;
            client.SendBufferSize = 4096;
            AsynchBuffer = new byte[8192];
            try
            {
                client.BeginConnect(IP_Adress, port, new AsyncCallback(ConnectCallback), client);
            }
            catch
            {
                Debug.Log("unable to connect to the server");
            }
        }
        private void ConnectCallback(IAsyncResult result)
        {
            try
            {
                client.EndConnect(result);
                if (client.Connected == false)
                {
                    return;
                }
                else
                {
                    mystream = client.GetStream();
                    mystream.BeginRead(AsynchBuffer,0,8192,OnRecieveData,null);
                    IsConnected = true;
                    Debug.Log("You are connected to the server successfully!");
                }
            }
            catch (Exception)
            {
                IsConnected = false;
                return;
            }

        }

        private void OnRecieveData(IAsyncResult result)
        {
            try
            {
                int packetlength = mystream.EndRead(result);
                Receivebyte = new byte[packetlength];
                Buffer.BlockCopy(AsynchBuffer, 0, Receivebyte, 0, packetlength);

                if (packetlength == 0)
                {
                   Debug.Log("disconnected");
                    Application.Quit();
                    return;
                }
                handleData = true;
                mystream.BeginRead(AsynchBuffer, 0, 8192, OnRecieveData, null);
            }
            catch (Exception)
            {
                Debug.Log("disconnected");
                Application.Quit();
                return;
            }

        }
    }

【问题讨论】:

标签: c# unity3d networking tcpclient


【解决方案1】:

问题出在这里:

    if (packets.TryGetValue(packetIdentifier, out packet))
    {
        packet.Invoke(data);
    }

为了避免这个错误,你可以使用

    if (packets.TryGetValue(packetIdentifier, out packet))
    {
        packet?.Invoke(data);
    }

但问题是我看不到您在代码中的数据填充数据包字典的位置。 你能展示你的ByteBuffer 课程吗?

【讨论】:

    猜你喜欢
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2016-06-05
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2014-07-21
    相关资源
    最近更新 更多