quakeball/Assets/Scripts/TeaNet/Peers/Peer.cs
2020-08-05 20:45:34 +03:00

112 lines
3.6 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using NeonTea.Quakeball.TeaNet.Packets;
namespace NeonTea.Quakeball.TeaNet.Peers {
public class Peer : PeerMessageListener {
public UdpClient UdpClient { get; private set; }
public byte[] Fingerprint { get; private set; }
public ListenerThread ListenerThread;
public ConnectionManager ConnectionManager;
public Dictionary<byte, Protocol> RegisteredProtocols = new Dictionary<byte, Protocol>();
public PeerMessageListener MessageListener;
public Peer(byte[] fingerprint) {
Fingerprint = fingerprint;
ConnectionManager = new ConnectionManager(this);
MessageListener = this;
}
public void Start(int sending_port) {
UdpClient = new UdpClient(sending_port);
MessageListener.Message("UdpClient Started");
}
public void Stop() {
ConnectionManager.StopThread();
if (ListenerThread != null) {
ListenerThread.Stop();
}
UdpClient.Dispose();
UdpClient.Close();
}
public void StartListen(string address, int port) {
IPEndPoint endpoint = new IPEndPoint(FindAddress(address), port);
StartListen(endpoint);
}
private void StartListen(IPEndPoint endpoint) {
if (ListenerThread != null) {
return; // Cant listen twice
}
ListenerThread = new ListenerThread(this, endpoint);
ListenerThread.Start();
MessageListener.Message($"Started listening to {endpoint}");
}
public void Connect(string address, int port, byte protocolIdent, bool startListening = true) {
if (startListening) {
IPEndPoint listenEndpoint = (IPEndPoint)UdpClient.Client.LocalEndPoint;
StartListen(listenEndpoint);
}
IPEndPoint endpoint = new IPEndPoint(FindAddress(address), port);
ConnectionManager.StartConnection(endpoint, protocolIdent);
MessageListener.Message($"Connecting to {endpoint}");
}
public void SendReliable(ulong uid, Packet packet) {
ConnectionManager.AddPacketToQueue(uid, packet);
ConnectionManager.SendPacketQueue(uid);
}
public void SendUnreliable(ulong uid, Packet packet) {
ConnectionManager.SendSingleUnreliable(uid, packet);
}
public Connection GetConnection(ulong uid) {
return ConnectionManager.GetConnection(uid);
}
public byte RegisterProtocol(Protocol protocol) {
byte ident = protocol.Identifier;
if (RegisteredProtocols.ContainsKey(ident)) {
return 0;
}
RegisteredProtocols.Add(ident, protocol);
protocol.Peer = this;
return ident;
}
public Protocol GetProtocol(byte ident) {
if (RegisteredProtocols.ContainsKey(ident)) {
return RegisteredProtocols[ident];
}
return null;
}
public void Message(string msg) {
}
public IPAddress FindAddress(string host) {
IPAddress addr;
try {
addr = Dns.GetHostAddresses(host)[0];
} catch (ArgumentException) {
addr = IPAddress.Parse(host);
}
return addr;
}
}
public interface PeerMessageListener {
void Message(string msg);
}
}