2017-11-21 18:33:48 +01:00
|
|
|
using Godot;
|
2017-11-21 22:23:12 +01:00
|
|
|
using System.Threading;
|
|
|
|
using Thread = System.Threading.Thread;
|
2017-11-21 18:33:48 +01:00
|
|
|
|
|
|
|
public abstract class Peer : Object {
|
|
|
|
|
2017-11-21 22:23:12 +01:00
|
|
|
private static PacketPeerUDP PacketPeer;
|
|
|
|
private static Peer Singleton;
|
2017-11-21 18:33:48 +01:00
|
|
|
private int LastConnectionSended = -1;
|
2017-11-21 22:23:12 +01:00
|
|
|
private Thread ListenerThread;
|
2017-11-21 18:33:48 +01:00
|
|
|
|
|
|
|
public Peer(PacketPeerUDP packetPeer) {
|
|
|
|
PacketPeer = packetPeer;
|
|
|
|
}
|
|
|
|
|
|
|
|
public abstract void Initialize(string address, int port);
|
|
|
|
public abstract void Update(float delta);
|
2017-11-21 22:23:12 +01:00
|
|
|
public abstract void ReceivePacket(byte[] buffer, string address, int port);
|
2017-11-21 18:33:48 +01:00
|
|
|
|
|
|
|
public void SendBuffer(byte[] buffer, Connection to) {
|
2017-11-21 22:23:12 +01:00
|
|
|
int temp1 = PacketPeer.SetDestAddress(to.Address, to.Port);
|
|
|
|
int temp2 = PacketPeer.PutPacket(buffer);
|
2017-11-21 18:33:48 +01:00
|
|
|
GD.print("Putting stuff to " + to.Address + ":" + to.Port);
|
2017-11-21 22:23:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
public bool StartListening(int port, string address = "*") {
|
|
|
|
if (PacketPeer.IsListening() || ListenerThread != null) {
|
|
|
|
GD.printerr("The Peer is already listening or the thread is active!");
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
Singleton = this;
|
|
|
|
PacketPeer.Listen(port, address);
|
|
|
|
ThreadStart ChildRef = new ThreadStart(ListenerThreadMethod);
|
|
|
|
ListenerThread = new Thread(ChildRef);
|
|
|
|
ListenerThread.Start();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void ListenerThreadMethod() {
|
|
|
|
GD.print("Started Listener Thread.");
|
|
|
|
while (true) {
|
|
|
|
PacketPeer.Wait();
|
|
|
|
byte[] Buffer = PacketPeer.GetPacket();
|
|
|
|
string Address = PacketPeer.GetPacketIp();
|
|
|
|
int Port = PacketPeer.GetPacketPort();
|
|
|
|
Singleton.ReceivePacket(Buffer, Address, Port);
|
|
|
|
}
|
2017-11-21 18:33:48 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|