' NetworkClient发送没有连接'尝试从客户端向服务器发送消息时出错

时间:2017-10-20 02:55:50

标签: c# unity3d networking network-programming

我尝试将自定义网络消息从我的客户端发送到我的服务器,并且我在行client.Send(AnimalDataMsgType.animalData, animalData);上的SendTexture()函数中收到错误

NetworkClient Send with no connection UnityEngine.Networking.NetworkClient:Send(Int16, MessageBase) Client:SendTexture(Texture2D, String, String, Int32, Int32) (at Assets/Scripts/Client.cs:158) Client:SendOnButtonPress() (at Assets/Scripts/Client.cs:141) UnityEngine.EventSystems.EventSystem:Update()

我刚刚开始学习团结网络的各个方面,所以我不知道我在哪里出错了。我已经完成了初始化NetworkTransport的一切,而我的客户端正在连接到我的服务器,所以我很困惑为什么我没有连接错误。我真的很感激任何可以帮助我解决这个问题的人。下面附带客户端和服务器端脚本。谢谢!

客户端

public class Client : NetworkBehaviour {

    NetworkClient client = new NetworkClient();

    private const int MAX_CONNECTION = 100;

    private string serverIP = "127.0.0.1";
    private int port = 5708;
    private int hostId;
    private int webHostId;
    private int reliableChannel;
    private int reliableSeqChannel;
    private int reliableFragChannel;
    private int unreliableChannel;
    private int unreliableSeqChannel;

    private string playerName;
    private int connectionId;
    private float connectionTime;
    private bool isStarted = false;
    private bool isConnected = false;
    private byte error;

    private GameObject infoDisplayText;

    public Texture2D texToSend;
    string typeToSend = "Deer";
    string idToSend = "1";
    int strengthToSend = 80;
    int hitPointsToSend = 2;

    private void Start()
    {
        infoDisplayText = GameObject.Find("InfoDisplay");
    }

    public void Connect()
    {
        NetworkTransport.Init();

        ConnectionConfig cc = new ConnectionConfig();

        reliableChannel = cc.AddChannel(QosType.Reliable);
        reliableSeqChannel = cc.AddChannel(QosType.ReliableSequenced);
        reliableFragChannel = cc.AddChannel(QosType.ReliableFragmented);
        unreliableChannel = cc.AddChannel(QosType.Unreliable);
        unreliableSeqChannel = cc.AddChannel(QosType.UnreliableSequenced);

        HostTopology topo = new HostTopology(cc, MAX_CONNECTION);

        hostId = NetworkTransport.AddHost(topo, 0);

        // Run client/server on different machines
        //hostID = NetworkTransport.AddHost(topo, port, null);  

        connectionId = NetworkTransport.Connect(hostId, serverIP, port, 0, out error);

        infoDisplayText = GameObject.Find("InfoDisplay");
        infoDisplayText.GetComponent<Text>().text += playerName + " connected.\n";

        connectionTime = Time.time;
        isConnected = true;
    }

    private void Update()
    {
        if (!isConnected)
            return;

        int recHostId, connectionId, channelId;
        byte[] recBuffer = new byte[1024];
        int bufferSize = 1024;
        int dataSize;
        byte error;

        NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);

        switch (recData)
        {
            case NetworkEventType.ConnectEvent:
                Debug.Log("Player " + connectionId + " has connected");
                infoDisplayText.GetComponent<Text>().text += "Connected to Server.\n";
                break;
        }
    }

    public void SendOnButtonPress()
    {
        SendTexture(texToSend, typeToSend, idToSend, strengthToSend, hitPointsToSend);
    }

    public void SendTexture(Texture2D tex, string type, string id, int strength, int hitpoints)
    {
        AnimalData animalData = new AnimalData();

        animalData.Tex = tex.GetRawTextureData();
        animalData.Type = type;
        animalData.Id = id;
        animalData.Strength = strength;
        animalData.Hitpoints = hitpoints;

        client.Connect(serverIP, port);
        client.Send(AnimalDataMsgType.animalData, animalData);
    }
}

服务器

public class Server : NetworkBehaviour
{
    private const int MAX_CONNECTION = 100;
    private int port = 5708;
    private int hostId;
    private int webHostId;
    private int reliableChannel;
    private int reliableSeqChannel;
    private int reliableFragChannel;
    private int unreliableChannel;
    private int unreliableSeqChannel;

    private bool isStarted = false;
    private byte error;

    private GameObject infoDisplayText;

    private void Awake()
    {
        infoDisplayText = GameObject.Find("InfoDisplay");
    }

    private void Start()
    {
        NetworkTransport.Init();

        ConnectionConfig cc = new ConnectionConfig();

        reliableChannel = cc.AddChannel(QosType.Reliable);
        reliableSeqChannel = cc.AddChannel(QosType.ReliableSequenced);
        reliableFragChannel = cc.AddChannel(QosType.ReliableFragmented);
        unreliableChannel = cc.AddChannel(QosType.Unreliable);
        unreliableSeqChannel = cc.AddChannel(QosType.UnreliableSequenced);

        HostTopology topo = new HostTopology(cc, MAX_CONNECTION);

        hostId = NetworkTransport.AddHost(topo, port, null);

        if (NetworkTransport.IsStarted)
        {
            isStarted = true;
            Debug.Log("NetworkTransport is Started.");
            infoDisplayText.GetComponent<Text>().text += "NetworkTransport is Started.\n";
        }

        Debug.Log("Server Started.");
        infoDisplayText.GetComponent<Text>().text += "Server Started.\n";

        setupRegisterHandler();
    }
    private void Update()
    {
        if (!isStarted)
            return;

        int recHostId, connectionId, channelId;
        byte[] recBuffer = new byte[1024];
        int bufferSize = 1024;
        int dataSize;
        byte error;

        NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);

        switch (recData)
        {
            case NetworkEventType.ConnectEvent:
                Debug.Log("Player " + connectionId + " has connected");
                infoDisplayText.GetComponent<Text>().text += "Player " + connectionId + " has connected\n";
                break;
        }
    }

    // Create a client and connect to the server port
    public void setupRegisterHandler()
    {
        NetworkServer.Listen(port);
        Debug.Log("Registering server callbacks");
        NetworkServer.RegisterHandler(AnimalDataMsgType.animalData, OnTextureReceive);
    }

    //Called when texture is received
    public void OnTextureReceive(NetworkMessage netMsg)
    {
        AnimalData animalData = netMsg.ReadMessage<AnimalData>();

        string type = animalData.Type;
        Debug.Log("Type : " + type);

        string id = animalData.Id;
        Debug.Log("ID : " + id);

        int strength = animalData.Strength;
        Debug.Log("Strength : " + strength);

        int hitpoints = animalData.Hitpoints;
        Debug.Log("Hit Points : " + hitpoints);

        //Your Received Texture2D
        Texture2D receivedtexture = new Texture2D(1280, 1024);
        receivedtexture.LoadRawTextureData(animalData.Tex);
        receivedtexture.Apply();

        Debug.Log(type + " data received!");
        infoDisplayText.GetComponent<Text>().text += type + " data received!\n";
    }
}

玩家类

public class Player : MessageBase
{
    public GameObject Avatar;

    public byte[] Tex;      // data coming from CanvasController
    public string Type;     // data coming from CanvasController
    public string Id;       // data coming from GameManager
    public int Strength;    // data coming from PlayerController
    public int Hitpoints;   // data coming from PlayerController
    public bool IsAlive;    // data coming from PlayerController
}

1 个答案:

答案 0 :(得分:1)

您同时调用这两行:

client.Connect(serverIP, port);
client.Send(AnimalDataMsgType.animalData, animalData);

通常,连接功能需要一些时间来建立连接。因此,当您在连接功能之后调用发送功能时,连接尚未建立。
所以,你可以遵循这种方法:
 1.首先调用连接功能  2.连接成功后,它会调用回调方法 OnConnected  3.你在 OnConnected 中制作一个bool true,就像isConnected = true;  4.在致电发送之前,检查isConnected是否为真;
更多详情:https://docs.unity3d.com/ScriptReference/Networking.NetworkClient.Connect.html