forked from CodeSpartan/MMOKitPersistenceServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseRPC.cs
More file actions
93 lines (80 loc) · 2.87 KB
/
Copy pathBaseRPC.cs
File metadata and controls
93 lines (80 loc) · 2.87 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
using System.Collections;
using System.Text;
using Newtonsoft.Json;
namespace PersistenceServer
{
abstract public class BaseRpc
{
public RpcType RpcType = RpcType.RpcUndef;
protected MmoWsServer? Server;
public void SubscribeToMessages(MmoWsServer inServer)
{
Server = inServer;
inServer.OnMessageReceived += TryTrigger;
}
private void TryTrigger(RpcType inRpcType, UserConnection conn, BinaryReader reader)
{
if (RpcType == inRpcType)
{
ReadRpc(conn, reader);
}
}
// Override in subclasses: read from the reader, then add an action to server.Processor.ConQ
// E.g.: server.processor.ConQ.Enqueue(() => Console.WriteLine("ah"));
protected virtual void ReadRpc(UserConnection connection, BinaryReader reader) { }
/*
* Technical functions that help serialize messages
*/
public static byte[] MergeByteArrays(params object[] list)
{
int totalBytesLength = 0;
for (int i = 0; i < list.Length; i++)
totalBytesLength += ((byte[])list[i]).Length;
byte[] result = new byte[totalBytesLength];
int pos = 0;
for (int i = 0; i < list.Length; i++)
{
byte[] thisArray = (byte[])list[i];
thisArray.CopyTo(result, pos);
pos += thisArray.Length;
}
return result;
}
public static byte[] ToBytes(RpcType rpc)
{
return new[] { (byte)rpc };
}
// Encodes a string into a binary array and prefixes it with an integer for string length
// So for example Hello will look as follows:
// 00000000 00000000 00000000 00000101 (which is 5, the number of bytes in 'Hello')
// 01001000 01100101 01101100 01101100 01101111 (which is 'Hello' itself)
public static byte[] WriteMmoString(string str)
{
return MergeByteArrays(ToBytes(Encoding.UTF8.GetBytes(str).Length), Encoding.UTF8.GetBytes(str));
}
public static byte[] ToBytes(int num)
{
byte[] bytes = BitConverter.GetBytes(num);
return bytes;
}
public static byte[] ToBytes(int[] intArray)
{
byte[] result = new byte[intArray.Length * sizeof(int)];
Buffer.BlockCopy(intArray, 0, result, 0, result.Length);
return result;
}
public static byte[] ToBytes(float num)
{
byte[] bytes = BitConverter.GetBytes(num);
if (!BitConverter.IsLittleEndian)
{
bytes = bytes.Reverse().ToArray();
}
return bytes;
}
public static byte[] ToBytes(bool b)
{
return BitConverter.GetBytes(b);
}
}
}