-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathEnetServerConnection.cs
104 lines (84 loc) · 2.91 KB
/
EnetServerConnection.cs
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.Collections.Generic;
using System.Net;
using DarkRift;
using DarkRift.Server;
using ENet;
public class EnetServerConnection : NetworkServerConnection {
//Whether we're connected
public override ConnectionState ConnectionState
{
get { return connectionState; }
}
private ConnectionState connectionState;
private readonly IPEndPoint[] remoteEndPoints;
//A list of endpoints we're connected to on the server
public override IEnumerable<IPEndPoint> RemoteEndPoints
{
get
{
return remoteEndPoints;
}
}
public EnetServerConnection(Peer peer)
{
this.peer = peer;
remoteEndPoints = new[] {new IPEndPoint(IPAddress.Parse(peer.IP), peer.Port)};
}
private Peer peer;
//Given a named endpoint this should return that
public override IPEndPoint GetRemoteEndPoint(string name)
{
throw new ArgumentException("Not a valid endpoint name!");
}
public override void StartListening()
{
}
public override bool SendMessageReliable(MessageBuffer message)
{
byte[] data = new byte[message.Count];
Array.Copy(message.Buffer, message.Offset, data, 0, message.Count);
message.Dispose();
return SendReliable(data, 1, peer);
}
public override bool SendMessageUnreliable(MessageBuffer message)
{
byte[] data = new byte[message.Count];
Array.Copy(message.Buffer, message.Offset, data, 0, message.Count);
message.Dispose();
return SendUnreliable(data, 2, peer);
}
//Called when the server wants to disconnect the client
public override bool Disconnect()
{
peer.Disconnect(0);
return true;
}
public void OnDisconnect()
{
HandleDisconnection();
}
//We should call HandleMessageReceived(MessageBuffer message, SendMode sendMode) when we get a new message from the client
//And HandleDisconnection(...) if the client disconnects
private bool SendReliable(byte[] data, byte channelID, Peer peer)
{
Packet packet = default(Packet);
packet.Create(data, data.Length, PacketFlags.Reliable | PacketFlags.NoAllocate); // Reliable Sequenced
return peer.Send(channelID, ref packet);
}
private bool SendUnreliable(byte[] data, byte channelID, Peer peer)
{
Packet packet = default(Packet);
packet.Create(data, data.Length, PacketFlags.None | PacketFlags.NoAllocate); // Unreliable Sequenced
return peer.Send(channelID, ref packet);
}
public void HandleEnetMessageReceived(Event netEvent, SendMode mode)
{
MessageBuffer message = MessageBuffer.Create(netEvent.Packet.Length);
netEvent.Packet.CopyTo(message.Buffer);
message.Offset = 0;
message.Count = netEvent.Packet.Length;
HandleMessageReceived(message, mode);
message.Dispose();
}
}