greyBow
greyBow

Reputation: 1348

Unity Client not connecting to host

I'm trying to connect a network client to a host using unity but I'm getting false returned through the debug check Debug.Log(myClient.isConnected.ToString());. I'm creating a new client and connecting with the method setupClient() but I guess I'm doing something incorrectly. How can I fix this? Am I debugging this correctly?

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");
    }
}

Upvotes: 0

Views: 2506

Answers (1)

Programmer
Programmer

Reputation: 125445

Am I debugging this correctly?

No, and you are not using NetworkClient.isConnected correctly.

The NetworkClient.Connect function is asynchronous which means that when you call it, it does not wait or block for that connection to actually connect. It uses a Thread to do the connection and when you use NetworkClient.isConnected right after calling NetworkClient.Connect, you will get unexpected result.

NetworkClient notifies you with a callback function when it is connected. The callback function is registered with the NetworkClient.RegisterHandler and MsgType.Connect. In your case, it is registered to the OnConnected function so OnConnected should be called when you are connected to the network.

You either have to start a coroutine and use NetworkClient.isConnected inside that coroutine function to wait for the connection like this:

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

or use the callback function (OnConnected) to detect when the client is connected.


Unrelated but it would be extremely useful to also subscribe to Error and Disconnect events too. These are important when troubleshooting your network code.

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);
}

Upvotes: 2

Related Questions