-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathEnetListenerPlugin.cs
94 lines (79 loc) · 2.84 KB
/
EnetListenerPlugin.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
using System;
using System.Collections.Generic;
using DarkRift;
using DarkRift.Server;
using ENet;
using UnityEngine;
using Event = ENet.Event;
using EventType = ENet.EventType;
public class EnetListenerPlugin : NetworkListener
{
public EnetListenerPlugin(NetworkListenerLoadData pluginLoadData) : base(pluginLoadData)
{
Version = new Version(1,0,0);
}
public override Version Version { get; }
public override void StartListening()
{
Library.Initialize();
server = new Host();
Address address = new Address();
address.Port = 4296;
server.Create(address, 50);
}
private Host server;
private Dictionary<Peer, EnetServerConnection> connections = new Dictionary<Peer, EnetServerConnection>();
public void ServerTick()
{
bool hasEvents = true;
while (hasEvents)
{
Event netEvent;
server.Service(0,out netEvent);
//Debug.Log("server: "+ netEvent.Type);
switch (netEvent.Type)
{
case EventType.None:
hasEvents = false;
break;
case EventType.Connect:
EnetServerConnection con = new EnetServerConnection(netEvent.Peer);
RegisterConnection(con);
connections.Add(netEvent.Peer, con);
Console.WriteLine("Client: "+ netEvent.Peer.IP + netEvent.Peer.Port+" connected.");
break;
case EventType.Disconnect:
HandleDisconnection(netEvent);
break;
case EventType.Timeout:
HandleDisconnection(netEvent);
break;
case EventType.Receive:
Console.WriteLine("Packet received from client - Channel ID: " + netEvent.ChannelID +
", Data length: " + netEvent.Packet.Length);
if (netEvent.ChannelID == 1)
{
connections[netEvent.Peer].HandleEnetMessageReceived(netEvent, SendMode.Reliable);
}
else if (netEvent.ChannelID == 2)
{
connections[netEvent.Peer].HandleEnetMessageReceived(netEvent, SendMode.Unreliable);
}
netEvent.Packet.Dispose();
break;
}
}
server.Flush();
}
void HandleDisconnection(Event netEvent)
{
Console.WriteLine("Client: " + netEvent.Peer.IP + netEvent.Peer.Port + " disconnected.");
connections[netEvent.Peer].OnDisconnect();
connections.Remove(netEvent.Peer);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
server.Dispose();
}
}