quakeball/Assets/Scripts/Net/Peers/Peer.cs
2020-08-05 04:21:04 +03:00

97 lines
3.0 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using NeonTea.Quakeball.Net.Packets;
using System.Threading.Tasks;
using System.Runtime.Remoting;
namespace NeonTea.Quakeball.Net.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) {
ListenerThread = new ListenerThread(this, endpoint);
ListenerThread.Start();
MessageListener.Message($"Started listening to {endpoint}");
}
public void Connect(string address, int port, byte protocolIdent) {
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 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);
}
}