-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkPacket.cs
More file actions
104 lines (88 loc) · 2.92 KB
/
NetworkPacket.cs
File metadata and controls
104 lines (88 loc) · 2.92 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
using System;
using System.Net.Sockets;
using System.Text;
namespace Network
{
class NetworkPacket
{
byte[] buffer = new byte[4096];
int bufferIndex = 0;
NetworkStream stream;
public string name;
public NetworkPacket(string name)
{
this.name = name;
WriteString(name);
}
public void WriteInt(int intNumber)
{
byte[] byteValue = BitConverter.GetBytes(intNumber);
Array.Copy(byteValue, 0, buffer, bufferIndex, sizeof(int));
bufferIndex += sizeof(int);
}
public void WriteFloat(float floatNumber)
{
byte[] byteValue = BitConverter.GetBytes(floatNumber);
Array.Copy(byteValue, 0, buffer, bufferIndex, sizeof(float));
bufferIndex += sizeof(float);
}
public void WriteString(string str)
{
WriteInt(str.Length);
byte[] byteValue = Encoding.ASCII.GetBytes(str);
Array.Copy(byteValue, 0, buffer, bufferIndex, byteValue.Length);
bufferIndex += byteValue.Length;
}
public NetworkPacket(byte[] buffer)
{
this.buffer = buffer;
name = ReadString();
}
public int ReadInt()
{
byte[] byteValue = new byte[sizeof(int)];
Array.Copy(buffer, bufferIndex, byteValue, 0, sizeof(int));
bufferIndex += sizeof(int);
return BitConverter.ToInt32(byteValue, 0);
}
public float ReadFloat()
{
byte[] byteValue = new byte[sizeof(float)];
Array.Copy(buffer, bufferIndex, byteValue, 0, sizeof(float));
bufferIndex += sizeof(float);
return BitConverter.ToSingle(byteValue, 0);
}
public string ReadString()
{
int length = ReadInt();
byte[] byteValue = new byte[length];
Array.Copy(buffer, bufferIndex, byteValue, 0, byteValue.Length);
bufferIndex += byteValue.Length;
return Encoding.ASCII.GetString(byteValue);
}
public void SendToServer()
{
if (!LocalClient.IsConnected())
return;
LocalClient.networkStream.BeginWrite(buffer, 0, bufferIndex, null, null);
}
public void SendToClient(Client client)
{
if (!client.IsConnected())
return;
try
{
client.networkStream.BeginWrite(buffer, 0, bufferIndex, null, null);
}
catch
{
}
}
public void SendToClients()
{
foreach (Client client in Server.clients)
if (client.IsConnected())
SendToClient(client);
}
}
}