Advertisement
Learning000001

Untitled

Jun 10th, 2024
347
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.41 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using Microsoft.AspNetCore.SignalR.Client;
  4. using Newtonsoft.Json;
  5. using UnityEngine;
  6. using Task = System.Threading.Tasks.Task;
  7.  
  8. public class SocketServerCommunication : MonoBehaviour
  9. {
  10.     public static Action OnOpponentJoinedRoom;
  11.     public static Action OnOpponentLeftRoom;
  12.     public static Action OnILeftRoom;
  13.    
  14.     public static SocketServerCommunication Instance;
  15.     private const string SERVER_URI = "https://api.qoomonquest.com/hubs/game";
  16.     private HubConnection connection;
  17.     private string authKey;
  18.  
  19.     public MatchData MatchData { get; private set; }
  20.  
  21.     private void Awake()
  22.     {
  23.         if (Instance==null)
  24.         {
  25.             Instance = this;
  26.         }
  27.         else
  28.         {
  29.             Destroy(gameObject);
  30.         }
  31.     }
  32.    
  33.     public void SetAuthToken(string _authKey)
  34.     {
  35.         authKey = _authKey;
  36.     }
  37.  
  38.     public async void Init(Action<bool> _callBack)
  39.     {
  40.         connection = new HubConnectionBuilder()
  41.             .WithUrl(SERVER_URI
  42.                 , _options =>
  43.             {
  44.                 _options.AccessTokenProvider = () => Task.FromResult(authKey);
  45.             }
  46.                 )
  47.             .WithAutomaticReconnect()
  48.             .Build();
  49.  
  50.         connection.On<string>(nameof(UserDisconnectedAsync), UserDisconnectedAsync);        
  51.         connection.On<string>(nameof(UserRejoinedAsync), UserRejoinedAsync);
  52.         connection.On<string>(nameof(UserLeftAsync), UserLeftAsync);
  53.         connection.On<List<string>>(nameof(ReceiveOldMessagesAsync), ReceiveOldMessagesAsync);
  54.         connection.On<string>(nameof(ReceiveMessageAsync), ReceiveMessageAsync);  
  55.         connection.On<bool>(nameof(MatchLeftAsync), MatchLeftAsync);  
  56.         connection.On<string,string,string>(nameof(MatchFoundAsync), MatchFoundAsync);
  57.         connection.On(nameof(MatchMakingStartedAsync),MatchMakingStartedAsync);
  58.  
  59.         try
  60.         {
  61.             await connection.StartAsync();
  62.             _callBack?.Invoke(true);
  63.         }
  64.         catch (Exception _error)
  65.         {
  66.             Debug.Log($"Trying to connect with: {SERVER_URI} , authToken: {authKey}\nFailed with error: {_error}");
  67.             _callBack?.Invoke(false);
  68.         }
  69.     }
  70.  
  71.     #region Receive messages
  72.  
  73.     private void UserDisconnectedAsync(string _userName)
  74.     {
  75.         Debug.Log("UserDisconnectedAsync: "+_userName);
  76.         OnOpponentLeftRoom?.Invoke();
  77.     }
  78.    
  79.     private void UserLeftAsync(string _userName)
  80.     {
  81.         Debug.Log("UserDisconnectedAsync: "+_userName);
  82.         OnOpponentLeftRoom?.Invoke();
  83.     }
  84.  
  85.     private void UserRejoinedAsync(string _userName)
  86.     {
  87.         Debug.Log("UserRejoinedAsync: "+_userName);
  88.     }
  89.    
  90.     private void MatchLeftAsync(bool _status)
  91.     {
  92.         if (!_status)
  93.         {
  94.             Debug.Log("Failed to leave room");
  95.             return;
  96.         }
  97.  
  98.         OnILeftRoom?.Invoke();
  99.     }
  100.  
  101.     private void ReceiveOldMessagesAsync(List<string> _messages)
  102.     {
  103.         Debug.Log("ReceiveOldMessagesAsync: ");
  104.         foreach (var _message in _messages)
  105.         {
  106.             Debug.Log(_message);
  107.         }
  108.     }
  109.    
  110.     private void ReceiveMessageAsync(string _message)
  111.     {
  112.         Debug.Log("ReceiveMessageAsync: "+_message);
  113.         ExecuteMessage(JsonConvert.DeserializeObject<MessageData>(_message));
  114.     }
  115.  
  116.     private void MatchFoundAsync(string _roomName, string _firstPlayer, string _secondPlayer)
  117.     {
  118.         Debug.Log($"MatchFoundAsync: {_firstPlayer} vs {_secondPlayer}");
  119.         MatchData = new MatchData() { RoomName = _roomName,Players = new List<string>() { _firstPlayer, _secondPlayer } };
  120.         OnOpponentJoinedRoom?.Invoke();
  121.     }
  122.    
  123.     private void MatchMakingStartedAsync()
  124.     {
  125.         Debug.Log($"MatchMakingStartedAsync");
  126.     }
  127.  
  128.  
  129.     #endregion
  130.  
  131.  
  132.     #region Send messages
  133.  
  134.     public new void SendMessage(string _message)
  135.     {
  136.         connection.SendAsync("SendMessageAsync", MatchData.RoomName,_message);
  137.     }
  138.  
  139.     public void StartMatchMaking()
  140.     {
  141.         connection.SendAsync("MatchMakeAsync");
  142.     }
  143.  
  144.     public void LeaveRoom()
  145.     {
  146.         connection.SendAsync("LeaveMatchAsync");
  147.     }
  148.    
  149.     #endregion
  150.  
  151.  
  152.     public void RegisterMessage(GameObject _object, string _functionName, string _data= null)
  153.     {
  154.         MessageData _message = new MessageData { GameObjectName = _object.name, MethodName = _functionName, Data = _data };
  155.         string _messageJson = JsonConvert.SerializeObject(_message);
  156.         SendMessage(_messageJson);
  157.     }
  158.  
  159.     private void ExecuteMessage(MessageData _messageData)
  160.     {
  161.         string _objectName = _messageData.GameObjectName;
  162.         GameObject _targetObject = GameObject.Find(_objectName);
  163.         if (_targetObject==null)
  164.         {
  165.             Debug.LogError($"GameObject {_objectName} not found.");
  166.         }
  167.        
  168.         MonoBehaviour _target = _targetObject.GetComponent<MonoBehaviour>();
  169.         if (_target == null)
  170.         {
  171.             Debug.LogError($"No MonoBehaviour found on object {_objectName}.");
  172.         }
  173.  
  174.         string _methodName = _messageData.MethodName;
  175.        
  176.         try
  177.         {
  178.             _target.SendMessage(_methodName,_messageData.Data);
  179.         }
  180.         catch (Exception _e)
  181.         {
  182.             Debug.LogError($"Failed to call {_methodName} on {_objectName}: "+_e);
  183.             throw;
  184.         }
  185.     }
  186. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement