-1

I'm trying/learning about networking with unity and I have run into this error:

NullReferenceException: Object reference not set to an instance of an object
ClientController.ConnectToServer () (at Assets/Scripts/ClientController.cs:61)
ClientController.Start () (at Assets/Scripts/ClientController.cs:38)

The code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System;


public class ClientController : MonoBehaviour
{
    [Header("Server info")]
    public string websiteUrl = "http://localhost/game/index.php";
    public static string serverAddress = "";
    public const int serverPort = 100;
    public static bool isConnected = false;
    [Space(10)]
    public bool maintinenceMode = false;
    public static string serverVersion = "";
    [Header("Client info")]
    public static string clientIPv4 = IPManager.GetIP(ADDRESSFAM.IPv4);
    public static string clientIPv6 = IPManager.GetIP(ADDRESSFAM.IPv6);
    public static string clientVersion = "0.0.0"; // Need to add client version checker
    [Space(10)]
    public string clientUser;
    public string clientPass;
    [Space(10)]
    public string clientChar1;
    public string clientChar2;
    public string clientChar3;

    public static Socket _clientSocket;

    void Start()
    {
        ServerRequest();
        ConnectToServer();
        ServerInfoRequest(0, null);
        ServerInfoRequest(1, clientVersion);
    }

    // Update is called once per frame
    void Update()
    {

    }

    IEnumerator ServerRequest()
    {
        WWWForm form = new WWWForm();
        form.AddField("serverReq", "Please");
        var download = UnityWebRequest.Post(websiteUrl, form);
        yield return download.SendWebRequest();
        serverAddress = download.downloadHandler.text.ToString();
    }

    private static void ConnectToServer()
    {
        int attempts = 0;
        while (!_clientSocket.Connected)
        {
            try
            {
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress remoteIPAddress = IPAddress.Parse(serverAddress);
                IPEndPoint remoteEndPoint = new IPEndPoint(remoteIPAddress, serverPort);
                _clientSocket.Connect(remoteEndPoint);
                attempts++;
            }
            catch (SocketException)
            {
                Debug.Log("Connection attempts: " + attempts.ToString());
            }
        }
        Debug.Log("Connected!");
        isConnected = true;
    }

    private static void ServerInfoRequest(int requsetType, string comparableData)
    {
        // Check
        byte[] buffer = Encoding.ASCII.GetBytes(requsetType.ToString());
        _clientSocket.Send(buffer);
        byte[] receivedBuf = new byte[1024];
        int rec = _clientSocket.Receive(receivedBuf);
        byte[] data = new byte[rec];
        Array.Copy(receivedBuf, data, rec);
        string reply = Encoding.ASCII.GetString(data);
        switch (requsetType)
        {
            // Check for maintinence
            case 0:
                Debug.Log("Checking for maintinence...");
                Debug.Log("Maintinence = " + reply);
                break;
            // Check server version
            case 1:
                Debug.Log("Checking for server version...");
                Debug.Log("Server version = " + reply);
                serverVersion = reply;
                int compareVersions = string.Compare(clientVersion, reply);
                Debug.Log("Client is compatibility is: " + compareVersions.ToString());
                break;
            default:
                Debug.Log("Unknown capabilities rising...");
                break;
        }
    }
}



I can't seem to figure out why the error occurs, I am kind of green around the ears but eager to learn. Line 61 is:

while (!_clientSocket.Connected)

I can't seem to figure out why I get the error, any help would be greatly appreciated!

Thanks in advance for any help!

1 Answers1

2

_clientSocket is never assigned, and you call .Connect on it, which is 'the same' as null.Connected. That's why you get a NullReferenceException.

I will suggest you to do as the following :

private static void ConnectToServer()
    {
        int attempts = 0;

        // Add a null check
        while (_clientSocket == null || !_clientSocket.Connected)
        {
            try
            {
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress remoteIPAddress = IPAddress.Parse(serverAddress);
                IPEndPoint remoteEndPoint = new IPEndPoint(remoteIPAddress, serverPort);
                _clientSocket.Connect(remoteEndPoint);
                attempts++;
            }
            catch (SocketException)
            {
                Debug.Log("Connection attempts: " + attempts.ToString());
            }
        }
        Debug.Log("Connected!");
        isConnected = true;
    }
Malphegal
  • 262
  • 1
  • 5
  • 9