Unity客户端未连接到主机

时间:2017-10-06 00:11:54

标签: c# unity3d networking

我正在尝试使用unity将网络客户端连接到主机,但是我通过调试检查Debug.Log(myClient.isConnected.ToString());得到了错误。我正在创建一个新客户端并使用方法setupClient()进行连接,但我想我做错了什么。我怎样才能解决这个问题?我正确调试了吗?

using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.NetworkSystem;

public class MyMsgType
{
    public static short texture = MsgType.Highest + 1;
};

//Create a class that holds a variables to send
public class TextureMessage : MessageBase
{
    public byte[] textureBytes;
    public string message = "Test Received Message"; //Optional
}

public class UNETChat : Chat
{
    NetworkClient myClient;
    public Texture2D previewTexture;
    string messageToSend = "Screen Short Image";

    private void Start()
    {
        //if the client is also the server
        if (NetworkServer.active) 
        {
            // Register to connect event
            myClient.RegisterHandler(MsgType.Connect, OnConnected);
            // Register to texture receive event
            myClient.RegisterHandler(MyMsgType.texture, OnTextureReceive);
        }
        setupClient();
    }

    public void DoSendTexture()
    {
        StartCoroutine(TakeSnapshot(Screen.width, Screen.height));
    }

    WaitForEndOfFrame frameEnd = new WaitForEndOfFrame();

    public IEnumerator TakeSnapshot(int width, int height)
    {
        yield return frameEnd;

        Texture2D texture = new Texture2D(800, 800, TextureFormat.RGB24, true);
        texture.ReadPixels(new Rect(0, 0, 800, 800), 0, 0);
        texture.LoadRawTextureData(texture.GetRawTextureData());
        texture.Apply();

        Debug.Log("Texture size is : " + texture.EncodeToPNG().Length);

        sendTexture(texture, messageToSend);

        // gameObject.renderer.material.mainTexture = TakeSnapshot;
    }

    //Call to send the Texture and a simple string message
    public void sendTexture(Texture2D texture, string message)
    {
        TextureMessage msg = new TextureMessage();

        //Convert Texture2D to byte array
        msg.textureBytes = texture.GetRawTextureData();
        msg.message = message;

        NetworkServer.SendToAll(MyMsgType.texture, msg);

        Debug.Log("Texture Sent!!");
    }

    // Create a client and connect to the server port
    public void setupClient()
    {
        Debug.Log("Setup Client");
        //Create new client
        myClient = new NetworkClient();
        //Register to connect event
        myClient.RegisterHandler(MsgType.Connect, OnConnected);
        //Register to texture receive event
        myClient.RegisterHandler(MyMsgType.texture, OnTextureReceive);
        //Connect to server
        myClient.Connect("localhost", 4444);

        Debug.Log(myClient.isConnected.ToString());
    }

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

        //Your Received message
        string message = msg.message;

        Debug.Log("Texture Messsage " + message);

        //Your Received Texture2D
        Texture2D receivedtexture = new Texture2D(4, 4);
        receivedtexture.LoadRawTextureData(msg.textureBytes);
        receivedtexture.Apply();
    }

    public void OnConnected(NetworkMessage netMsg)
    {
        Debug.Log("Connected to server");
    }
}

1 个答案:

答案 0 :(得分:2)

  

我是否正确调试了这个?

不,您没有正确使用NetworkClient.isConnected

NetworkClient.Connect函数是异步的,这意味着当您调用它时,它不会等待或阻止该连接实际连接。它使用线程进行连接,当您在调用NetworkClient.isConnected后立即使用NetworkClient.Connect时,您将获得意外结果。

NetworkClient在连接时会通过回调函数通知您。回调函数已在NetworkClient.RegisterHandlerMsgType.Connect中注册。在您的情况下,它已注册到OnConnected函数,因此当您连接到网络时应调用OnConnected

您必须启动协程并在该协程函数中使用NetworkClient.isConnected来等待这样的连接:

while(!NetworkClient.isConnected)
{
    Debug.Log("Waiting for Connection");
    yield return null;
}
Debug.Log("Connected");

或使用回调函数(OnConnected)来检测客户端何时连接。

不相关,但也订阅Error和Disconnect事件也非常有用。在对网络代码进行故障排除时,这些非常重要。

myClient.RegisterHandler(MsgType.Error, OnError);
myClient.RegisterHandler(MsgType.Disconnect, OnDisconnect);

...

private void OnError(NetworkMessage netMsg)
{
    ErrorMessage error = netMsg.ReadMessage<ErrorMessage>();
    Debug.Log("Error while connecting: " + error.errorCode);
}

private void OnDisconnect(NetworkMessage netMsg)
{
    ErrorMessage error = netMsg.ReadMessage<ErrorMessage>();
    Debug.Log("Disconnected: " + error.errorCode);
}