0
\$\begingroup\$

I building a realtime multiplayer game like a small quiz game that players can able to join the game and then quiz master who handling the host will launch the game. I need to that how to do this functionality. This is my server script.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.Types;
using UnityEngine.Networking.Match;
public class Server : MonoBehaviour
{
    #region Variables

    //CONSTANTS
    private const int MAX_CONECTIONS = 40;
    private const string SERVER_IP = "127.0.0.1";
    private const int SERVER_PORT = 8999;
    private const int SERVER_WEB_PORT = 8998;
    private const int BUFFER_SIZE = 1024;
    private const int BYTE_SIZE = 1024;

    //CHANNELS
    private int reliableChannelID;
    private int unReliableChannelID;

    //HOSTS
    private int hostID;
    private int webHostID;


    //LOGIC
    private bool isInit;
    private byte[] buffer = new byte[BUFFER_SIZE];

    private byte error;

    //GAME FUNCTION
    public bool gameStarted;
    public bool isStarted;
    private float startTime = 10f;
    private float timer;

    List<MatchInfo> matchList = new List<MatchInfo>();
    bool matchCreated;
    NetworkMatch networkMatch;

    #endregion

    //CLASS REFERENCES
    ButtonScript gameStartObject = new ButtonScript();
    CountDown countDown = new CountDown();

    string timerCountDown;

    //HOSTING FUNCTION REFERENCE
    private string monthName;
    private string roomname;

    void Awake()
    {
        networkMatch = gameObject.AddComponent<NetworkMatch>();
    }

    private void Start()
    {
        monthName = (DateTime.Now.Month).ToString("MMM");
        roomname = ("HNB Quiz Mania - " + monthName);
        Debug.Log(roomname);
        GlobalConfig confing = new GlobalConfig();
        NetworkTransport.Init(confing);

        //HOST TOPOLOGY
        ConnectionConfig connectionConfig = new ConnectionConfig();
        reliableChannelID = connectionConfig.AddChannel(QosType.Reliable);
        unReliableChannelID = connectionConfig.AddChannel(QosType.Unreliable);
        HostTopology topology = new HostTopology(connectionConfig, MAX_CONECTIONS);

        //ADDING HOSTS
        hostID = NetworkTransport.AddHost(topology, SERVER_PORT); // when adding the connection in actual server, -> hostID/webHostID = NetworkTransport.AddHost(topology, SERVER_PORT/SERVER_WEB_PORT,BINDINGHOSTIP);
        webHostID = NetworkTransport.AddWebsocketHost(topology, SERVER_WEB_PORT);

        isInit = true;
        Debug.Log("Starting the serer");

        //SETTING TIMER TO QUESTION RESERVED TIME
        timerCountDown = countDown.timeLeft.ToString("F2");
        gameStarted = gameStartObject.isStartGameCliked;
    }

    // Update is called once per frame
    private void Update()
    {
        if (!isInit) { return; }

        #region Local Variables
        int outHostId;
        int outConnectionId;
        int outChannelId;

        int receivedSize;
        byte error;
        byte[] buffer = new byte[256];
        #endregion

        NetworkEventType evt = NetworkTransport.Receive(out outHostId, out outConnectionId, out outChannelId, buffer, buffer.Length, out receivedSize, out error);

        if (evt == NetworkEventType.Nothing) { return; } //If there is no event, terminate the process

        #region UpdateMessagePump

        switch (evt)
        {
            case NetworkEventType.ConnectEvent:
                {
                    Debug.Log("Conntection from : " + outConnectionId + " through the channel : " + outChannelId);
                    Debug.Log(string.Format("User {0} has connected", outConnectionId));
                    break;
                }//When somebody connected and still dont have a connection ID and all the other information to be connected to a server, hard to have the full context around the user untill they connects. 
            case NetworkEventType.DisconnectEvent:
                {
                    Debug.Log("Disconntection from : " + outConnectionId + " through the channel : " + outChannelId);
                    Debug.Log(string.Format("User {0} has disconnected", outConnectionId));
                    break;
                }   //
            case NetworkEventType.DataEvent:
                {
                    Debug.Log("Data from : " + outConnectionId + " through the channel : " + outChannelId + "::Message::" + buffer);
                    DataEvent(buffer);
                    break;
                }
            case NetworkEventType.BroadcastEvent:
                {
                    Debug.Log("Unexpected Nettwork event type" + evt);
                    break;
                }
            case NetworkEventType.Nothing:
                {
                    return;
                }

            default:

                Debug.Log("Unknown Nettwork message type recieved : " + evt);
                break;
        } 

        #endregion

        if (gameStarted)
        {
            Debug.Log("Calling timer");
            StartGameQuiz(gameStarted);
        }
        else
        {
            Debug.Log("...Game hasn't started yet...");
        }

        Debug.Log("client countdown : " + timerCountDown);
        Debug.Log("client countdown test 2: " + countDown.timeLeft.ToString("F2"));



    }

    public void UpdatemessagePump()
    {
        if (!isStarted) { return; }

        int recHostID;      //Which platform
        int connectionID;   //Which User Sending the message
        int channelID;      //Which Lane used to send the specific message

        byte[] recBuffer = new byte[BYTE_SIZE];
        int dataSize;

        NetworkEventType type = NetworkTransport.Receive(out recHostID, out connectionID, out channelID, recBuffer, BYTE_SIZE, out dataSize, out error);

        switch (type)
        {
            case NetworkEventType.Nothing:
                {
                    break;
                }
            case NetworkEventType.ConnectEvent:
                {
                    Debug.Log(string.Format("User {0} has connected",connectionID));
                    break;
                }
            case NetworkEventType.DisconnectEvent:
                {
                    Debug.Log(string.Format("User {0} has disconnected", connectionID));
                    break;
                }   //
            case NetworkEventType.DataEvent:
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    MemoryStream memoryStream = new MemoryStream(recBuffer);
                    NetMessage message = (NetMessage)formatter.Deserialize(memoryStream);

                    OnData(connectionID, channelID, recHostID, message);
                    break;
                }

            default:
            case NetworkEventType.BroadcastEvent:
                Debug.Log("Unexpected Nettwork event type" + type);
                break;
        }
    }

    void DataEvent(byte[] dataBuffer)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream memoryStream = new MemoryStream(dataBuffer);
        NetMessage message = (NetMessage)formatter.Deserialize(memoryStream);
    }


    #region OnData
    private void OnData(int connectionID, int channelID, int recHostID, NetMessage message)
    {
        switch (message.OperationCode)
        {
            case NetOperationCode.none:
                Debug.Log("Unexpected Network Operation");
                break;

            case NetOperationCode.createAccount:
                CreateAccount(connectionID, channelID, recHostID, (Net_CreateAccount)message);
                break;
        }
    }

    private void CreateAccount(int connectionID, int channelID, int recHostID, Net_CreateAccount createAccountMessage)
    {
        Debug.Log("create account message");
        Debug.Log(string.Format("{0},{1},{2}", createAccountMessage.username, createAccountMessage.password, createAccountMessage.sessionID));
    }

    #endregion

    public void StartGameQuiz(bool gameStared)
    {
            Debug.Log("Quiz begun");

    }

    #region SendingData
    public void SendClient(int recHostID, int connectionID, NetMessage message)
    {
        //data hodler
        byte[] dataBuffer = new byte[BYTE_SIZE];

        //crushing data to byte array
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream memoryStream = new MemoryStream(dataBuffer);
        formatter.Serialize(memoryStream, message);

        if(recHostID == 0)
        {
            NetworkTransport.Send(hostID, connectionID, reliableChannelID, dataBuffer, BYTE_SIZE, out error);
        }

        else
        {
            NetworkTransport.Send(webHostID, connectionID, reliableChannelID, dataBuffer, BYTE_SIZE, out error);
        }

    }


    #endregion

}

And this is my client script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class Client : MonoBehaviour
{
    #region Variables

    //CONSTANTS
    private const int MAX_CONECTIONS = 40;
    private const string SERVER_IP = "127.0.0.1";
    private const int SERVER_PORT = 8999;
    private const int SERVER_WEB_PORT = 8998;
    private const int BUFFER_SIZE = 1024;

    private const int BYTE_SIZE = 1024;

    //CHANNELS
    private int reliableChannelID;
    private int unReliableChannelID;

    //HOSTS
    private int hostID;
    private int connectionID;


    //LOGIC
    private bool isConnected;
    private byte[] buffer = new byte[BUFFER_SIZE];

    private byte error;
    #endregion
    private bool isStarted;
    // Start is called before the first frame update
    private void Start()
    {
        //getting the msg that server is started or not
        ButtonScript gameObject = new ButtonScript();

        GlobalConfig confing = new GlobalConfig();
        NetworkTransport.Init(confing);

        //HOST TOPOLOGY
        ConnectionConfig connectionConfig = new ConnectionConfig();
        reliableChannelID = connectionConfig.AddChannel(QosType.Reliable);
        unReliableChannelID = connectionConfig.AddChannel(QosType.Unreliable);
        HostTopology topology = new HostTopology(connectionConfig, MAX_CONECTIONS);

        //CONNECTING TO HOSTS
        hostID = NetworkTransport.AddHost(topology, 0); //DEFINE WHAT CONNECTION TO BE SYNC WITH AND TO CARRY TOPOLOGY IN SAME NETWORK MAP

        //Standalone client
#if UNITY_WEBGL
    //WEBGL client
    connectionID = NetworkTransport.Connect(hostID, SERVER_IP, SERVER_WEB_PORT, 0, out error);
#else
        //Standalone client

        connectionID = NetworkTransport.Connect(hostID, SERVER_IP, SERVER_PORT, 0, out error);
#endif

        isStarted = gameObject.isStartGameCliked;

        if (isStarted)
        {
            Debug.Log("Server is online and Game is now starting");
        }
    }

    private void Update()
    {
        UpdatemessagePump();
    }

    public void UpdatemessagePump()
    {
        if (!isStarted) { return; }

        int recHostID;      //Which platform
        int connectionID;   //Which User Sending the message
        int channelID;      //Which Lane used to send the specific message

        byte[] recBuffer = new byte[BYTE_SIZE];
        int dataSize;

        NetworkEventType type = NetworkTransport.Receive(out recHostID, out connectionID, out channelID, recBuffer, BYTE_SIZE, out dataSize, out error);

        switch (type)
        {
            case NetworkEventType.Nothing:
                {
                    break;
                }
            case NetworkEventType.ConnectEvent:
                {
                    Debug.Log(string.Format(" connected to the server", connectionID));
                    break;
                }
            case NetworkEventType.DisconnectEvent:
                {
                    Debug.Log(string.Format("disconnected from the server", connectionID));
                    break;
                }   //
            case NetworkEventType.DataEvent:
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    MemoryStream memoryStream = new MemoryStream(recBuffer);
                    NetMessage message = (NetMessage)formatter.Deserialize(memoryStream);

                    OnData(connectionID, channelID, recHostID, message);

                    break;
                }

            default:
            case NetworkEventType.BroadcastEvent:
                Debug.Log("Unexpected Nettwork event type" + type);
                break;
        }
    }

    #region OnData
    private void OnData(int connectionID, int channelID, int recHostID, NetMessage message)
    {
        switch (message.OperationCode)
        {
            case NetOperationCode.none:
                Debug.Log("Unexpected Network Operation");
                break;

        }

    }

    #endregion

    #region SendingData
    public void SendServer(NetMessage message)
    {
        //data hodler
        byte[] dataBuffer = new byte[BYTE_SIZE];

        //crushing data to byte array
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream memoryStream = new MemoryStream(dataBuffer);
        formatter.Serialize(memoryStream, message);

        NetworkTransport.Send(hostID, connectionID, reliableChannelID, dataBuffer, BYTE_SIZE, out error);
    } 
    #endregion

    public void TESTFUNCTIONCREATEACCOUNT()
    {
        Net_CreateAccount createAccount = new Net_CreateAccount();
        createAccount.username = "Sakuna";
        createAccount.password = "test1234";
        createAccount.sessionID = "quiz+week+1+0";

        SendServer(createAccount);

    }
}

This script gives the message that connection has been established to the server. What I need is, when host start the game, each client will able to start at the same time.

Would anybody please help on this...? Any advises will be really helpfull. My unity version is 2019.2

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.