forked from GlaireDaggers/Netcode.IO.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatagramQueue.cs
More file actions
91 lines (74 loc) · 1.67 KB
/
Copy pathDatagramQueue.cs
File metadata and controls
91 lines (74 loc) · 1.67 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
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using NetcodeIO.NET.Utils.IO;
namespace NetcodeIO.NET.Utils
{
internal struct Datagram
{
public byte[] payload;
public int payloadSize;
public EndPoint sender;
public void Release()
{
BufferPool.ReturnBuffer(payload);
}
}
internal class DatagramQueue
{
protected Queue<Datagram> datagramQueue = new Queue<Datagram>();
protected Queue<EndPoint> endpointPool = new Queue<EndPoint>();
private object datagram_mutex = new object();
private object endpoint_mutex = new object();
private IPAddress defaultAnyAddress;
public DatagramQueue(IPAddress defaultAnyAddress)
{
this.defaultAnyAddress = defaultAnyAddress;
}
public int Count
{
get
{
return datagramQueue.Count;
}
}
public void Clear()
{
datagramQueue.Clear();
endpointPool.Clear();
}
public void ReadFrom( Socket socket )
{
EndPoint sender;
lock (endpoint_mutex)
{
if (endpointPool.Count > 0)
sender = endpointPool.Dequeue();
else
sender = new IPEndPoint(defaultAnyAddress, 0);
}
byte[] receiveBuffer = BufferPool.GetBuffer(2048);
int recv = socket.ReceiveFrom(receiveBuffer, ref sender);
if (recv > 0)
{
Datagram packet = new Datagram();
packet.sender = sender;
packet.payload = receiveBuffer;
packet.payloadSize = recv;
lock (datagram_mutex)
datagramQueue.Enqueue(packet);
}
}
public void Enqueue(Datagram datagram)
{
lock(datagram_mutex)
datagramQueue.Enqueue(datagram);
}
public Datagram Dequeue()
{
lock(datagram_mutex)
return datagramQueue.Dequeue();
}
}
}