-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerCommunication.cs
More file actions
184 lines (165 loc) · 6.36 KB
/
ServerCommunication.cs
File metadata and controls
184 lines (165 loc) · 6.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
using UnityEngine;
using System.IO;
using System;
using System.Text;
using System.Collections.Generic;
using UnityEngine.UI;
/// <summary>
/// Forefront class for the server communication.
/// </summary>
public class ServerCommunication
{
// Server IP address
[SerializeField]
public string hostIP;
// Server port
[SerializeField]
public int port = 3000;
// Flag to use localhost
[SerializeField]
public bool useLocalhost = true;
// Address used in code
public string host => useLocalhost ? "localhost" : hostIP;
public string path = "";
// Final server address
public string server;
// WebSocket Client
public WsClient client;
public bool isOwner;
// Class with messages for "lobby"
public LobbyMessaging Lobby { private set; get; }
public string logFileName;
public bool ssl = false;
/// <summary>
/// Unity method called on initialization
/// </summary>
public ServerCommunication(){}
public void Init(){
isOwner = false;
string time = string.Format("{0:yyyy-MM-dd HH-mm-ss}", DateTime.Now);
logFileName = $"session_{time}.log";
server = (ssl ? "wss" : "ws") + "://" + host + ":" + port + "/" + path;
client = new WsClient(server);
// Messaging
Lobby = new LobbyMessaging(this);
}
/// <summary>
/// Unity method called every frame
/// </summary>
public void Update()
{
// Check if server send new messages
var cqueue = client.receiveQueue;
byte[] msg;
if (Bridge.IsSimulating()) return;
while (cqueue.TryPeek(out msg))
{
// Parse newly received messages
cqueue.TryDequeue(out msg);
HandleMessage(msg);
}
}
/// <summary>
/// Method responsible for handling server messages
/// </summary>
/// <param name="msg">Message.</param>
public void HandleMessage(byte[] msg)
{
//Debug.Log("<CLIENT> <RECV>: " + msg);
// Deserializing message from the server
int offset = 0;
var message = new MessageModel(msg, ref offset);
// Picking correct method for message handling
if (message.metadata == "server_closed"){
MultiplayerMod.MultiplayerMod.Disconnect();
}
if (message.metadata == "owner"){
isOwner = true;
}
if (message.metadata == "connected"){
MultiplayerMod.MultiplayerMod.syncLayout();
}
offset = 0;
//Debug.Log(message.type);
switch (message.type)
{
case LobbyMessaging.BridgeAction:
Lobby.OnBridgeAction?.Invoke(new BridgeActionModel(message.content, ref offset));
break;
case "ConnectionResponse":
MultiplayerMod.MultiplayerMod.GUIValues.ConnectionResponse = MultiplayerMod.MultiplayerMod.GetJustStringFromBytes(message.content);
break;
case LobbyMessaging.ServerInfo:
MultiplayerMod.MultiplayerMod.instance.serverInfo = new ServerInfoModel(message.content, ref offset);
MultiplayerMod.MultiplayerMod.RemoveDisconnectedUsersFromMousePositions();
break;
case LobbyMessaging.KickUser:
MultiplayerMod.MultiplayerMod.GUIValues.kickResponse = MultiplayerMod.MultiplayerMod.GetJustStringFromBytes(message.content);
break;
case LobbyMessaging.ServerConfig:
MultiplayerMod.MultiplayerMod.GUIValues.ConfigResponse = MultiplayerMod.MultiplayerMod.GetJustStringFromBytes(message.content);
break;
case LobbyMessaging.CreateInvite:
MultiplayerMod.MultiplayerMod.GUIValues.InviteResponse = MultiplayerMod.MultiplayerMod.GetJustStringFromBytes(message.content);
break;
case LobbyMessaging.MousePosition:
MousePositionModel mousePosition = new MousePositionModel(message.content, ref offset);
mousePosition.position.z = -1.1f;
MultiplayerMod.MultiplayerMod.instance.HandleMousePositionRecieved(mousePosition);
break;
case LobbyMessaging.PopupMessage:
PopUpMessage.DisplayOkOnly(MultiplayerMod.MultiplayerMod.GetJustStringFromBytes(message.content), null);
if (isOwner) MultiplayerMod.MultiplayerMod.ActionLog($"Popup Message - {message.content}");
break;
case LobbyMessaging.TopLeftMessage:
GameUI.ShowMessage(ScreenMessageLocation.TOP_LEFT, MultiplayerMod.MultiplayerMod.GetJustStringFromBytes(message.content), 3f);
if (isOwner) MultiplayerMod.MultiplayerMod.ActionLog($"Info Message - {message.content}");
break;
case LobbyMessaging.ChatMessage:
ChatMessageModel chatMessage = new ChatMessageModel(message.content, ref offset);
string color = "#" + ColorUtility.ToHtmlStringRGB(chatMessage.nameColor);
chatMessage.message = chatMessage.message.Replace("<", "<<i></i>");
MultiplayerMod.MultiplayerMod.ChatValues.chatLog += $"<color={color}>{chatMessage.username}</color>: {chatMessage.message}\n";
break;
default:
Debug.LogError("Unknown type of method: " + message.type);
break;
}
}
/// <summary>
/// Call this method to connect to the server
/// </summary>
public async void ConnectToServer()
{
await client.Connect();
}
public bool IsConnected(){
if (client != null){
return client.IsConnectionOpen();
}
return false;
}
public bool IsConnecting(){
if (client != null){
return client.IsConnecting();
}
return false;
}
/// <summary>
/// Method which sends data through websocket
/// </summary>
/// <param name="message">Message.</param>
public void SendRequest(byte[] message)
{
client.Send(message);
}
}
public class PointerHandler {
public PointerHandler(){
this.Container = MultiplayerMod.MultiplayerMod.Instantiate(new GameObject("cursorContainer"));
this.color = Color.red;
SpriteRenderer renderer = this.Container.AddComponent<SpriteRenderer>();
}
public GameObject Container;
public Color color;
}