Showing preview only (513K chars total). Download the full file or copy to clipboard to get everything.
Repository: RevenantX/NetGameExample
Branch: master
Commit: a3d06604ef8f
Files: 169
Total size: 470.1 KB
Directory structure:
gitextract_i90u_vd7/
├── .gitignore
├── .vscode/
│ └── settings.json
├── Assets/
│ ├── Code/
│ │ ├── Client/
│ │ │ ├── ClientLogic.cs
│ │ │ ├── ClientLogic.cs.meta
│ │ │ ├── ClientPlayer.cs
│ │ │ ├── ClientPlayer.cs.meta
│ │ │ ├── ClientPlayerManager.cs
│ │ │ ├── ClientPlayerManager.cs.meta
│ │ │ ├── ClientPlayerView.cs
│ │ │ ├── ClientPlayerView.cs.meta
│ │ │ ├── IPlayerView.cs
│ │ │ ├── IPlayerView.cs.meta
│ │ │ ├── RemotePlayer.cs
│ │ │ ├── RemotePlayer.cs.meta
│ │ │ ├── RemotePlayerView.cs
│ │ │ ├── RemotePlayerView.cs.meta
│ │ │ ├── ShootEffect.cs
│ │ │ ├── ShootEffect.cs.meta
│ │ │ ├── UiController.cs
│ │ │ └── UiController.cs.meta
│ │ ├── Client.meta
│ │ ├── Server/
│ │ │ ├── AntilagSystem.cs
│ │ │ ├── AntilagSystem.cs.meta
│ │ │ ├── ServerLogic.cs
│ │ │ ├── ServerLogic.cs.meta
│ │ │ ├── ServerPlayer.cs
│ │ │ ├── ServerPlayer.cs.meta
│ │ │ ├── ServerPlayerManager.cs
│ │ │ └── ServerPlayerManager.cs.meta
│ │ ├── Server.meta
│ │ ├── Shared/
│ │ │ ├── BasePlayer.cs
│ │ │ ├── BasePlayer.cs.meta
│ │ │ ├── BasePlayerManager.cs
│ │ │ ├── BasePlayerManager.cs.meta
│ │ │ ├── Collisions.cs
│ │ │ ├── Collisions.cs.meta
│ │ │ ├── Extensions.cs
│ │ │ ├── Extensions.cs.meta
│ │ │ ├── GamePackets.cs
│ │ │ ├── GamePackets.cs.meta
│ │ │ ├── GamePool.cs
│ │ │ ├── GamePool.cs.meta
│ │ │ ├── GameTimer.cs
│ │ │ ├── GameTimer.cs.meta
│ │ │ ├── LiteRingBuffer.cs
│ │ │ ├── LiteRingBuffer.cs.meta
│ │ │ ├── LogicTimer.cs
│ │ │ ├── LogicTimer.cs.meta
│ │ │ ├── NetworkGeneral.cs
│ │ │ └── NetworkGeneral.cs.meta
│ │ └── Shared.meta
│ ├── Code.meta
│ ├── Materials/
│ │ ├── ShootEffectMat.mat
│ │ └── ShootEffectMat.mat.meta
│ ├── Materials.meta
│ ├── Plugins/
│ │ ├── LiteNetLib/
│ │ │ ├── BaseChannel.cs
│ │ │ ├── BaseChannel.cs.meta
│ │ │ ├── ConnectionRequest.cs
│ │ │ ├── ConnectionRequest.cs.meta
│ │ │ ├── INetEventListener.cs
│ │ │ ├── INetEventListener.cs.meta
│ │ │ ├── Layers/
│ │ │ │ ├── Crc32cLayer.cs
│ │ │ │ ├── Crc32cLayer.cs.meta
│ │ │ │ ├── PacketLayerBase.cs
│ │ │ │ ├── PacketLayerBase.cs.meta
│ │ │ │ ├── XorEncryptLayer.cs
│ │ │ │ └── XorEncryptLayer.cs.meta
│ │ │ ├── Layers.meta
│ │ │ ├── NatPunchModule.cs
│ │ │ ├── NatPunchModule.cs.meta
│ │ │ ├── NetConstants.cs
│ │ │ ├── NetConstants.cs.meta
│ │ │ ├── NetDebug.cs
│ │ │ ├── NetDebug.cs.meta
│ │ │ ├── NetManager.cs
│ │ │ ├── NetManager.cs.meta
│ │ │ ├── NetPacket.cs
│ │ │ ├── NetPacket.cs.meta
│ │ │ ├── NetPacketPool.cs
│ │ │ ├── NetPacketPool.cs.meta
│ │ │ ├── NetPeer.cs
│ │ │ ├── NetPeer.cs.meta
│ │ │ ├── NetSocket.cs
│ │ │ ├── NetSocket.cs.meta
│ │ │ ├── NetStatistics.cs
│ │ │ ├── NetStatistics.cs.meta
│ │ │ ├── NetUtils.cs
│ │ │ ├── NetUtils.cs.meta
│ │ │ ├── ReliableChannel.cs
│ │ │ ├── ReliableChannel.cs.meta
│ │ │ ├── SequencedChannel.cs
│ │ │ ├── SequencedChannel.cs.meta
│ │ │ ├── Utils/
│ │ │ │ ├── CRC32C.cs
│ │ │ │ ├── CRC32C.cs.meta
│ │ │ │ ├── FastBitConverter.cs
│ │ │ │ ├── FastBitConverter.cs.meta
│ │ │ │ ├── INetSerializable.cs
│ │ │ │ ├── INetSerializable.cs.meta
│ │ │ │ ├── NetDataReader.cs
│ │ │ │ ├── NetDataReader.cs.meta
│ │ │ │ ├── NetDataWriter.cs
│ │ │ │ ├── NetDataWriter.cs.meta
│ │ │ │ ├── NetPacketProcessor.cs
│ │ │ │ ├── NetPacketProcessor.cs.meta
│ │ │ │ ├── NetSerializer.cs
│ │ │ │ ├── NetSerializer.cs.meta
│ │ │ │ ├── NtpPacket.cs
│ │ │ │ ├── NtpPacket.cs.meta
│ │ │ │ ├── NtpRequest.cs
│ │ │ │ └── NtpRequest.cs.meta
│ │ │ └── Utils.meta
│ │ └── LiteNetLib.meta
│ ├── Plugins.meta
│ ├── Prefabs/
│ │ ├── ClientPlayerPrefab.prefab
│ │ ├── ClientPlayerPrefab.prefab.meta
│ │ ├── RemotePlayerPrefab.prefab
│ │ ├── RemotePlayerPrefab.prefab.meta
│ │ ├── ShootEffect.prefab
│ │ └── ShootEffect.prefab.meta
│ ├── Prefabs.meta
│ ├── Scenes/
│ │ ├── SampleScene.unity
│ │ └── SampleScene.unity.meta
│ ├── Scenes.meta
│ ├── Sounds/
│ │ ├── death1.ogg
│ │ ├── death1.ogg.meta
│ │ ├── death2.ogg
│ │ ├── death2.ogg.meta
│ │ ├── death3.ogg
│ │ ├── death3.ogg.meta
│ │ ├── hit1.ogg
│ │ ├── hit1.ogg.meta
│ │ ├── hit2.ogg
│ │ ├── hit2.ogg.meta
│ │ ├── hit3.ogg
│ │ ├── hit3.ogg.meta
│ │ ├── shoot1.ogg
│ │ ├── shoot1.ogg.meta
│ │ ├── shoot2.ogg
│ │ ├── shoot2.ogg.meta
│ │ ├── shoot3.ogg
│ │ └── shoot3.ogg.meta
│ └── Sounds.meta
├── LICENSE
├── Packages/
│ ├── manifest.json
│ └── packages-lock.json
├── ProjectSettings/
│ ├── AudioManager.asset
│ ├── ClusterInputManager.asset
│ ├── DynamicsManager.asset
│ ├── EditorBuildSettings.asset
│ ├── EditorSettings.asset
│ ├── GraphicsSettings.asset
│ ├── InputManager.asset
│ ├── MemorySettings.asset
│ ├── NavMeshAreas.asset
│ ├── NetworkManager.asset
│ ├── PackageManagerSettings.asset
│ ├── Physics2DSettings.asset
│ ├── PresetManager.asset
│ ├── ProjectSettings.asset
│ ├── ProjectVersion.txt
│ ├── QualitySettings.asset
│ ├── TagManager.asset
│ ├── TimeManager.asset
│ ├── UnityConnectSettings.asset
│ ├── VFXManager.asset
│ ├── VersionControlSettings.asset
│ ├── XRSettings.asset
│ └── boot.config
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# This .gitignore file should be placed at the root of your Unity project directory
#
# Get latest from https://github.com/github/gitignore/blob/main/Unity.gitignore
#
/[Ll]ibrary/
/[Tt]emp/
/[Oo]bj/
/[Bb]uild/
/[Bb]uilds/
/[Ll]ogs/
/[Uu]ser[Ss]ettings/
# MemoryCaptures can get excessive in size.
# They also could contain extremely sensitive data
/[Mm]emoryCaptures/
# Recordings can get excessive in size
/[Rr]ecordings/
# Uncomment this line if you wish to ignore the asset store tools plugin
# /[Aa]ssets/AssetStoreTools*
# Autogenerated Jetbrains Rider plugin
/[Aa]ssets/Plugins/Editor/JetBrains*
# Visual Studio cache directory
.vs/
# JetBrains Rider cache directory
.idea/
# Gradle cache directory
.gradle/
# Autogenerated VS/MD/Consulo solution and project files
ExportedObj/
.consulo/
*.csproj
*.unityproj
*.sln
*.suo
*.tmp
*.user
*.userprefs
*.pidb
*.booproj
*.svd
*.pdb
*.mdb
*.opendb
*.VC.db
# Unity3D generated meta files
*.pidb.meta
*.pdb.meta
*.mdb.meta
# Unity3D generated file on crash reports
sysinfo.txt
# Builds
*.apk
*.aab
*.unitypackage
*.app
# Crashlytics generated file
crashlytics-build.properties
# Packed Addressables
/[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin*
# Temporary auto-generated Android Assets
/[Aa]ssets/[Ss]treamingAssets/aa.meta
/[Aa]ssets/[Ss]treamingAssets/aa/*
================================================
FILE: .vscode/settings.json
================================================
{
"files.exclude":
{
"**/.DS_Store":true,
"**/.git":true,
"**/.gitignore":true,
"**/.gitmodules":true,
"**/*.booproj":true,
"**/*.pidb":true,
"**/*.suo":true,
"**/*.user":true,
"**/*.userprefs":true,
"**/*.unityproj":true,
"**/*.dll":true,
"**/*.exe":true,
"**/*.pdf":true,
"**/*.mid":true,
"**/*.midi":true,
"**/*.wav":true,
"**/*.gif":true,
"**/*.ico":true,
"**/*.jpg":true,
"**/*.jpeg":true,
"**/*.png":true,
"**/*.psd":true,
"**/*.tga":true,
"**/*.tif":true,
"**/*.tiff":true,
"**/*.3ds":true,
"**/*.3DS":true,
"**/*.fbx":true,
"**/*.FBX":true,
"**/*.lxo":true,
"**/*.LXO":true,
"**/*.ma":true,
"**/*.MA":true,
"**/*.obj":true,
"**/*.OBJ":true,
"**/*.asset":true,
"**/*.cubemap":true,
"**/*.flare":true,
"**/*.mat":true,
"**/*.meta":true,
"**/*.prefab":true,
"**/*.unity":true,
"build/":true,
"Build/":true,
"Library/":true,
"library/":true,
"obj/":true,
"Obj/":true,
"ProjectSettings/":true,
"temp/":true,
"Temp/":true
}
}
================================================
FILE: Assets/Code/Client/ClientLogic.cs
================================================
using System;
using System.Net;
using System.Net.Sockets;
using Code.Shared;
using LiteNetLib;
using LiteNetLib.Utils;
using UnityEngine;
using UnityEngine.UI;
using Random = System.Random;
namespace Code.Client
{
public class ClientLogic : MonoBehaviour, INetEventListener
{
[SerializeField] private ClientPlayerView _clientPlayerViewPrefab;
[SerializeField] private RemotePlayerView _remotePlayerViewPrefab;
[SerializeField] private Text _debugText;
[SerializeField] private ShootEffect _shootEffectPrefab;
private Action<DisconnectInfo> _onDisconnected;
private GamePool<ShootEffect> _shootsPool;
private NetManager _netManager;
private NetDataWriter _writer;
private NetPacketProcessor _packetProcessor;
private string _userName;
private ServerState _cachedServerState;
private ShootPacket _cachedShootData;
private ushort _lastServerTick;
private NetPeer _server;
private ClientPlayerManager _playerManager;
private int _ping;
public static LogicTimer LogicTimer { get; private set; }
private ShootEffect ShootEffectContructor()
{
var eff = Instantiate(_shootEffectPrefab);
eff.Init(e => _shootsPool.Put(e));
return eff;
}
private void Awake()
{
DontDestroyOnLoad(gameObject);
Random r = new Random();
_cachedServerState = new ServerState();
_cachedShootData = new ShootPacket();
_userName = Environment.MachineName + " " + r.Next(100000);
LogicTimer = new LogicTimer(OnLogicUpdate);
_writer = new NetDataWriter();
_playerManager = new ClientPlayerManager(this);
_shootsPool = new GamePool<ShootEffect>(ShootEffectContructor, 100);
_packetProcessor = new NetPacketProcessor();
_packetProcessor.RegisterNestedType((w, v) => w.Put(v), reader => reader.GetVector2());
_packetProcessor.RegisterNestedType<PlayerState>();
_packetProcessor.SubscribeReusable<PlayerJoinedPacket>(OnPlayerJoined);
_packetProcessor.SubscribeReusable<JoinAcceptPacket>(OnJoinAccept);
_packetProcessor.SubscribeReusable<PlayerLeavedPacket>(OnPlayerLeaved);
_netManager = new NetManager(this)
{
AutoRecycle = true,
IPv6Enabled = IPv6Mode.Disabled
};
_netManager.Start();
}
private void OnLogicUpdate()
{
_playerManager.LogicUpdate();
}
private void Update()
{
_netManager.PollEvents();
LogicTimer.Update();
if (_playerManager.OurPlayer != null)
_debugText.text =
string.Format(
$"LastServerTick: {_lastServerTick}\n" +
$"StoredCommands: {_playerManager.OurPlayer.StoredCommands}\n" +
$"Ping: {_ping}");
else
_debugText.text = "Disconnected";
}
private void OnDestroy()
{
_netManager.Stop();
}
private void OnPlayerJoined(PlayerJoinedPacket packet)
{
Debug.Log($"[C] Player joined: {packet.UserName}");
var remotePlayer = new RemotePlayer(_playerManager, packet.UserName, packet);
var view = RemotePlayerView.Create(_remotePlayerViewPrefab, remotePlayer);
_playerManager.AddPlayer(remotePlayer, view);
}
private void OnServerState()
{
//skip duplicate or old because we received that packet unreliably
if (NetworkGeneral.SeqDiff(_cachedServerState.Tick, _lastServerTick) <= 0)
return;
_lastServerTick = _cachedServerState.Tick;
_playerManager.ApplyServerState(ref _cachedServerState);
}
private void OnShoot()
{
var p = _playerManager.GetById(_cachedShootData.FromPlayer);
if (p == null || p == _playerManager.OurPlayer)
return;
SpawnShoot(p.Position, _cachedShootData.Hit);
}
public void SpawnShoot(Vector2 from, Vector2 to)
{
var eff = _shootsPool.Get();
eff.Spawn(from, to);
}
private void OnPlayerLeaved(PlayerLeavedPacket packet)
{
var player = _playerManager.RemovePlayer(packet.Id);
if(player != null)
Debug.Log($"[C] Player leaved: {player.Name}");
}
private void OnJoinAccept(JoinAcceptPacket packet)
{
Debug.Log("[C] Join accept. Received player id: " + packet.Id);
_lastServerTick = packet.ServerTick;
var clientPlayer = new ClientPlayer(this, _playerManager, _userName, packet.Id);
var view = ClientPlayerView.Create(_clientPlayerViewPrefab, clientPlayer);
_playerManager.AddClientPlayer(clientPlayer, view);
}
public void SendPacketSerializable<T>(PacketType type, T packet, DeliveryMethod deliveryMethod) where T : INetSerializable
{
if (_server == null)
return;
_writer.Reset();
_writer.Put((byte)type);
packet.Serialize(_writer);
_server.Send(_writer, deliveryMethod);
}
public void SendPacket<T>(T packet, DeliveryMethod deliveryMethod) where T : class, new()
{
if (_server == null)
return;
_writer.Reset();
_writer.Put((byte) PacketType.Serialized);
_packetProcessor.Write(_writer, packet);
_server.Send(_writer, deliveryMethod);
}
void INetEventListener.OnPeerConnected(NetPeer peer)
{
Debug.Log("[C] Connected to server: " + peer.EndPoint);
_server = peer;
SendPacket(new JoinPacket {UserName = _userName}, DeliveryMethod.ReliableOrdered);
LogicTimer.Start();
}
void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
{
_playerManager.Clear();
_server = null;
LogicTimer.Stop();
Debug.Log("[C] Disconnected from server: " + disconnectInfo.Reason);
if (_onDisconnected != null)
{
_onDisconnected(disconnectInfo);
_onDisconnected = null;
}
}
void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError socketError)
{
Debug.Log("[C] NetworkError: " + socketError);
}
void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod)
{
byte packetType = reader.GetByte();
if (packetType >= NetworkGeneral.PacketTypesCount)
return;
PacketType pt = (PacketType) packetType;
switch (pt)
{
case PacketType.Spawn:
break;
case PacketType.ServerState:
_cachedServerState.Deserialize(reader);
OnServerState();
break;
case PacketType.Serialized:
_packetProcessor.ReadAllPackets(reader);
break;
case PacketType.Shoot:
_cachedShootData.Deserialize(reader);
OnShoot();
break;
default:
Debug.Log("Unhandled packet: " + pt);
break;
}
}
void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader,
UnconnectedMessageType messageType)
{
}
void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency)
{
_ping = latency;
}
void INetEventListener.OnConnectionRequest(ConnectionRequest request)
{
request.Reject();
}
public void Connect(string ip, Action<DisconnectInfo> onDisconnected)
{
_onDisconnected = onDisconnected;
_netManager.Connect(ip, 10515, "ExampleGame");
}
}
}
================================================
FILE: Assets/Code/Client/ClientLogic.cs.meta
================================================
fileFormatVersion: 2
guid: 4a77c76b7885899499706477e4e0eeb4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Code/Client/ClientPlayer.cs
================================================
using Code.Shared;
using LiteNetLib;
using UnityEngine;
namespace Code.Client
{
public class ClientPlayer : BasePlayer
{
private PlayerInputPacket _nextCommand;
private readonly ClientLogic _clientLogic;
private readonly ClientPlayerManager _playerManager;
private readonly LiteRingBuffer<PlayerInputPacket> _predictionPlayerStates;
private ServerState _lastServerState;
private const int MaxStoredCommands = 60;
private bool _firstStateReceived;
private int _updateCount;
public Vector2 LastPosition { get; private set; }
public float LastRotation { get; private set; }
public int StoredCommands => _predictionPlayerStates.Count;
public ClientPlayer(ClientLogic clientLogic, ClientPlayerManager manager, string name, byte id) : base(manager, name, id)
{
_playerManager = manager;
_predictionPlayerStates = new LiteRingBuffer<PlayerInputPacket>(MaxStoredCommands);
_clientLogic = clientLogic;
}
public void ReceiveServerState(ServerState serverState, PlayerState ourState)
{
if (!_firstStateReceived)
{
if (serverState.LastProcessedCommand == 0)
return;
_firstStateReceived = true;
}
if (serverState.Tick == _lastServerState.Tick ||
serverState.LastProcessedCommand == _lastServerState.LastProcessedCommand)
return;
_lastServerState = serverState;
//sync
_position = ourState.Position;
_rotation = ourState.Rotation;
if (_predictionPlayerStates.Count == 0)
return;
ushort lastProcessedCommand = serverState.LastProcessedCommand;
int diff = NetworkGeneral.SeqDiff(lastProcessedCommand,_predictionPlayerStates.First.Id);
//apply prediction
if (diff >= 0 && diff < _predictionPlayerStates.Count)
{
//Debug.Log($"[OK] SP: {serverState.LastProcessedCommand}, OUR: {_predictionPlayerStates.First.Id}, DF:{diff}");
_predictionPlayerStates.RemoveFromStart(diff+1);
foreach (var state in _predictionPlayerStates)
ApplyInput(state, LogicTimer.FixedDelta);
}
else if(diff >= _predictionPlayerStates.Count)
{
Debug.Log($"[C] Player input lag st: {_predictionPlayerStates.First.Id} ls:{lastProcessedCommand} df:{diff}");
//lag
_predictionPlayerStates.FastClear();
_nextCommand.Id = lastProcessedCommand;
}
else
{
Debug.Log($"[ERR] SP: {serverState.LastProcessedCommand}, OUR: {_predictionPlayerStates.First.Id}, DF:{diff}, STORED: {StoredCommands}");
}
}
public override void Spawn(Vector2 position)
{
base.Spawn(position);
}
public void SetInput(Vector2 velocity, float rotation, bool fire)
{
_nextCommand.Keys = 0;
if(fire)
_nextCommand.Keys |= MovementKeys.Fire;
if (velocity.x < -0.5f)
_nextCommand.Keys |= MovementKeys.Left;
if (velocity.x > 0.5f)
_nextCommand.Keys |= MovementKeys.Right;
if (velocity.y < -0.5f)
_nextCommand.Keys |= MovementKeys.Up;
if (velocity.y > 0.5f)
_nextCommand.Keys |= MovementKeys.Down;
_nextCommand.Rotation = rotation;
}
public override void Update(float delta)
{
LastPosition = _position;
LastRotation = _rotation;
_nextCommand.Id = (ushort)((_nextCommand.Id + 1) % NetworkGeneral.MaxGameSequence);
_nextCommand.ServerTick = _lastServerState.Tick;
ApplyInput(_nextCommand, delta);
if (_predictionPlayerStates.IsFull)
{
_nextCommand.Id = (ushort)(_lastServerState.LastProcessedCommand+1);
_predictionPlayerStates.FastClear();
}
_predictionPlayerStates.Add(_nextCommand);
_updateCount++;
if (_updateCount == 3)
{
_updateCount = 0;
foreach (var t in _predictionPlayerStates)
_clientLogic.SendPacketSerializable(PacketType.Movement, t, DeliveryMethod.Unreliable);
}
base.Update(delta);
}
}
}
================================================
FILE: Assets/Code/Client/ClientPlayer.cs.meta
================================================
fileFormatVersion: 2
guid: aff1c62a30b048c9afcb6b247d10acc6
timeCreated: 1552515488
================================================
FILE: Assets/Code/Client/ClientPlayerManager.cs
================================================
using System.Collections.Generic;
using Code.Shared;
using UnityEngine;
namespace Code.Client
{
public struct PlayerHandler
{
public readonly BasePlayer Player;
public readonly IPlayerView View;
public PlayerHandler(BasePlayer player, IPlayerView view)
{
Player = player;
View = view;
}
public void Update(float delta)
{
Player.Update(delta);
}
}
public class ClientPlayerManager : BasePlayerManager
{
private readonly Dictionary<byte, PlayerHandler> _players;
private readonly ClientLogic _clientLogic;
private ClientPlayer _clientPlayer;
public ClientPlayer OurPlayer => _clientPlayer;
public override int Count => _players.Count;
public ClientPlayerManager(ClientLogic clientLogic)
{
_clientLogic = clientLogic;
_players = new Dictionary<byte, PlayerHandler>();
}
public override IEnumerator<BasePlayer> GetEnumerator()
{
foreach (var ph in _players)
yield return ph.Value.Player;
}
public void ApplyServerState(ref ServerState serverState)
{
for (int i = 0; i < serverState.PlayerStatesCount; i++)
{
var state = serverState.PlayerStates[i];
if(!_players.TryGetValue(state.Id, out var handler))
return;
if (handler.Player == _clientPlayer)
{
_clientPlayer.ReceiveServerState(serverState, state);
}
else
{
var rp = (RemotePlayer)handler.Player;
rp.OnPlayerState(state);
}
}
}
public override void OnShoot(BasePlayer from, Vector2 to, BasePlayer hit)
{
if(from == _clientPlayer)
_clientLogic.SpawnShoot(from.Position, to);
}
public BasePlayer GetById(byte id)
{
return _players.TryGetValue(id, out var ph) ? ph.Player : null;
}
public BasePlayer RemovePlayer(byte id)
{
if (_players.TryGetValue(id, out var handler))
{
_players.Remove(id);
handler.View.Destroy();
}
return handler.Player;
}
public override void LogicUpdate()
{
foreach (var kv in _players)
kv.Value.Update(LogicTimer.FixedDelta);
}
public void AddClientPlayer(ClientPlayer player, ClientPlayerView view)
{
_clientPlayer = player;
_players.Add(player.Id, new PlayerHandler(player, view));
}
public void AddPlayer(RemotePlayer player, RemotePlayerView view)
{
_players.Add(player.Id, new PlayerHandler(player, view));
}
public void Clear()
{
foreach (var p in _players.Values)
p.View.Destroy();
_players.Clear();
}
}
}
================================================
FILE: Assets/Code/Client/ClientPlayerManager.cs.meta
================================================
fileFormatVersion: 2
guid: b654f7e3a7ba40b0860b89829339a4b5
timeCreated: 1553432137
================================================
FILE: Assets/Code/Client/ClientPlayerView.cs
================================================
using UnityEngine;
namespace Code.Client
{
public class ClientPlayerView : MonoBehaviour, IPlayerView
{
[SerializeField] private TextMesh _name;
private ClientPlayer _player;
private Camera _mainCamera;
public static ClientPlayerView Create(ClientPlayerView prefab, ClientPlayer player)
{
Quaternion rot = Quaternion.Euler(0f, player.Rotation, 0f);
var obj = Instantiate(prefab, player.Position, rot);
obj._player = player;
obj._name.text = player.Name;
obj._mainCamera = Camera.main;
return obj;
}
private void Update()
{
var vert = Input.GetAxis("Vertical");
var horz = Input.GetAxis("Horizontal");
var fire = Input.GetAxis("Fire1");
Vector2 velocty = new Vector2(horz, vert);
Vector2 mousePos = _mainCamera.ScreenToWorldPoint(Input.mousePosition);
Vector2 dir = mousePos - _player.Position;
float rotation = Mathf.Atan2(dir.y, dir.x);
_player.SetInput(velocty, rotation, fire > 0f);
float lerpT = ClientLogic.LogicTimer.LerpAlpha;
transform.position = Vector2.Lerp(_player.LastPosition, _player.Position, lerpT);
float angle = Mathf.Lerp(_player.LastRotation, _player.Rotation, lerpT);
transform.rotation = Quaternion.Euler(0f, 0f, angle * Mathf.Rad2Deg );
}
public void Destroy()
{
Destroy(gameObject);
}
}
}
================================================
FILE: Assets/Code/Client/ClientPlayerView.cs.meta
================================================
fileFormatVersion: 2
guid: 34c60df172a14e9ba8eeb93c4b0789c8
timeCreated: 1552515543
================================================
FILE: Assets/Code/Client/IPlayerView.cs
================================================
namespace Code.Client
{
public interface IPlayerView
{
void Destroy();
}
}
================================================
FILE: Assets/Code/Client/IPlayerView.cs.meta
================================================
fileFormatVersion: 2
guid: 4be69af384c84c7892b27a41f0d59f23
timeCreated: 1553427365
================================================
FILE: Assets/Code/Client/RemotePlayer.cs
================================================
using Code.Shared;
using UnityEngine;
namespace Code.Client
{
public class RemotePlayer : BasePlayer
{
private readonly LiteRingBuffer<PlayerState> _buffer = new LiteRingBuffer<PlayerState>(30);
private float _receivedTime;
private float _timer;
private const float BufferTime = 0.1f; //100 milliseconds
public RemotePlayer(ClientPlayerManager manager, string name, PlayerJoinedPacket pjPacket) : base(manager, name, pjPacket.InitialPlayerState.Id)
{
_position = pjPacket.InitialPlayerState.Position;
_health = pjPacket.Health;
_rotation = pjPacket.InitialPlayerState.Rotation;
_buffer.Add(pjPacket.InitialPlayerState);
}
public override void Spawn(Vector2 position)
{
_buffer.FastClear();
base.Spawn(position);
}
public void UpdatePosition(float delta)
{
if (_receivedTime < BufferTime || _buffer.Count < 2)
return;
var dataA = _buffer[0];
var dataB = _buffer[1];
float lerpTime = NetworkGeneral.SeqDiff(dataB.Tick, dataA.Tick)*LogicTimer.FixedDelta;
float t = _timer / lerpTime;
_position = Vector2.Lerp(dataA.Position, dataB.Position, t);
_rotation = Mathf.Lerp(dataA.Rotation, dataB.Rotation, t);
_timer += delta;
if (_timer > lerpTime)
{
_receivedTime -= lerpTime;
_buffer.RemoveFromStart(1);
_timer -= lerpTime;
}
}
public void OnPlayerState(PlayerState state)
{
//old command
int diff = NetworkGeneral.SeqDiff(state.Tick, _buffer.Last.Tick);
if (diff <= 0)
return;
_receivedTime += diff * LogicTimer.FixedDelta;
if (_buffer.IsFull)
{
Debug.LogWarning("[C] Remote: Something happened");
//Lag?
_receivedTime = 0f;
_buffer.FastClear();
}
_buffer.Add(state);
}
}
}
================================================
FILE: Assets/Code/Client/RemotePlayer.cs.meta
================================================
fileFormatVersion: 2
guid: 0a420c02346543379e092fc538932775
timeCreated: 1552515495
================================================
FILE: Assets/Code/Client/RemotePlayerView.cs
================================================
using UnityEngine;
namespace Code.Client
{
public class RemotePlayerView : MonoBehaviour, IPlayerView
{
private RemotePlayer _player;
public static RemotePlayerView Create(RemotePlayerView prefab, RemotePlayer player)
{
Quaternion rot = Quaternion.Euler(0f, player.Rotation, 0f);
var obj = Instantiate(prefab, player.Position, rot);
obj._player = player;
return obj;
}
private void Update()
{
_player.UpdatePosition(Time.deltaTime);
transform.position = _player.Position;
transform.rotation = Quaternion.Euler(0f, 0f, _player.Rotation * Mathf.Rad2Deg );
}
public void Destroy()
{
Destroy(gameObject);
}
}
}
================================================
FILE: Assets/Code/Client/RemotePlayerView.cs.meta
================================================
fileFormatVersion: 2
guid: 79ae69e7e2264cea80924512389f864d
timeCreated: 1552862368
================================================
FILE: Assets/Code/Client/ShootEffect.cs
================================================
using System;
using Code.Shared;
using UnityEngine;
public class ShootEffect : MonoBehaviour
{
[SerializeField] private LineRenderer _trailRenderer;
[SerializeField] private AudioSource _source;
[SerializeField] private AudioSource _target;
[SerializeField] private AudioClip[] _shootClips;
[SerializeField] private AudioClip[] _hitClips;
private GameTimer _aliveTimer = new GameTimer(0.3f);
private Action<ShootEffect> _onDeathCallback;
private Vector3[] _positions = new Vector3[2];
public void Init(Action<ShootEffect> onDeathCallback)
{
_onDeathCallback = onDeathCallback;
gameObject.SetActive(false);
}
public void Spawn(Vector2 from, Vector2 to)
{
_source.transform.position = from;
_target.transform.position = to;
_trailRenderer.transform.position = from;
_positions[0] = from;
_positions[1] = to;
_trailRenderer.SetPositions(_positions);
gameObject.SetActive(true);
_source.PlayOneShot(_shootClips.GetRandomElement());
_target.PlayOneShot(_hitClips.GetRandomElement());
}
private void OnDeath()
{
_onDeathCallback(this);
gameObject.SetActive(false);
}
private void Update()
{
_aliveTimer.Update(Time.deltaTime, OnDeath);
float t1 = _aliveTimer.Time / _aliveTimer.MaxTime;
float t2 = _aliveTimer.Time / (_aliveTimer.MaxTime * 2f);
Color a = new Color(1f, 1f, 0f, 1f);
Color b = new Color(1f, 1f, 0f, 0f);
_trailRenderer.startColor = Color.Lerp(a, b, t1);
_trailRenderer.endColor = Color.Lerp(a, b, t2);
}
}
================================================
FILE: Assets/Code/Client/ShootEffect.cs.meta
================================================
fileFormatVersion: 2
guid: 2b4d80dfb54119b48b368fd5b60c6ab6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Code/Client/UiController.cs
================================================
using Code.Server;
using LiteNetLib;
using UnityEngine;
using UnityEngine.UI;
namespace Code.Client
{
public class UiController : MonoBehaviour
{
[SerializeField] private GameObject _uiObject;
[SerializeField] private ClientLogic _clientLogic;
[SerializeField] private ServerLogic _serverLogic;
[SerializeField] private InputField _ipField;
[SerializeField] private Text _disconnectInfoField;
private void Awake()
{
_ipField.text = NetUtils.GetLocalIp(LocalAddrType.IPv4);
}
public void OnHostClick()
{
_serverLogic.StartServer();
_uiObject.SetActive(false);
_clientLogic.Connect("localhost", OnDisconnected);
}
private void OnDisconnected(DisconnectInfo info)
{
_uiObject.SetActive(true);
_disconnectInfoField.text = info.Reason.ToString();
}
public void OnConnectClick()
{
_uiObject.SetActive(false);
_clientLogic.Connect(_ipField.text, OnDisconnected);
}
}
}
================================================
FILE: Assets/Code/Client/UiController.cs.meta
================================================
fileFormatVersion: 2
guid: 637a36ad5bdc47f47a5e5c0de52df2fc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Code/Client.meta
================================================
fileFormatVersion: 2
guid: 154eed4c1661601469c7de37e38b933a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Code/Server/AntilagSystem.cs
================================================
using System.Collections.Generic;
using UnityEngine;
namespace Code.Server
{
public struct StateInfo
{
public Vector2 Position;
}
public class AntilagSystem
{
private readonly Dictionary<int, StateInfo>[] _storedPositions;
private readonly Dictionary<int, StateInfo> _savedStates;
private int _currentArrayPos;
private ushort _lastTick;
private readonly int _maxTicks;
public AntilagSystem(int maxTicks, int maxPlayers)
{
int dictSize = (maxPlayers + 1)*3;
_maxTicks = maxTicks;
_storedPositions = new Dictionary<int, StateInfo>[maxTicks];
_savedStates = new Dictionary<int, StateInfo>(dictSize);
for (int i = 0; i < _storedPositions.Length; i++)
{
_storedPositions[i] = new Dictionary<int, StateInfo>(dictSize);
}
}
private Dictionary<int, StateInfo> GetStates(ushort tick)
{
if (tick < _lastTick - _maxTicks || _lastTick < _maxTicks)
return null;
return _storedPositions[(_currentArrayPos - _lastTick + tick - 1) % _maxTicks];
}
public void StorePositions(ushort serverTick, ServerPlayer[] players)
{
var currentDict = _storedPositions[_currentArrayPos];
currentDict.Clear();
foreach (var p in players)
{
if (!p.IsAlive)
continue;
StateInfo si = new StateInfo
{
Position = p.Position
};
currentDict.Add(p.AssociatedPeer.Id, si);
}
_lastTick = serverTick;
_currentArrayPos = (_currentArrayPos + 1) % _maxTicks;
}
public bool TryApplyAntilag(ServerPlayer[] players, ushort tick, int exceptId)
{
var antilagStates = GetStates(tick);
if (antilagStates == null)
return false;
_savedStates.Clear();
foreach (var p in players)
{
int id = p.AssociatedPeer.Id;
if (id == exceptId)
continue;
//Save current states
StateInfo state = new StateInfo
{
Position = p.Position
};
//Console.WriteLine("Save state {0} = {1} {2}", id, state.Position, state.Pose);
_savedStates[id] = state;
//Apply antilag
StateInfo antilagState;
if (antilagStates.TryGetValue(id, out antilagState))
{
//serverController.Player.ChangeState(antilagState.Position, antilagState.Pose, true);
}
}
return true;
}
public void RevertAntilag(ServerPlayer[] players)
{
//Revert states
foreach (var p in players)
{
StateInfo state;
if (_savedStates.TryGetValue(p.AssociatedPeer.Id, out state))
{
//Console.WriteLine("Load state {0} = {1} {2}", serverController.ServerId, state.Position, state.Pose);
//p.ChangeState(state.Position, state.Pose, true);
}
}
}
}
}
================================================
FILE: Assets/Code/Server/AntilagSystem.cs.meta
================================================
fileFormatVersion: 2
guid: 601c7fe5599c477ea58e6af0a0d7e91c
timeCreated: 1552862682
================================================
FILE: Assets/Code/Server/ServerLogic.cs
================================================
using System.Net;
using System.Net.Sockets;
using Code.Shared;
using LiteNetLib;
using LiteNetLib.Utils;
using UnityEngine;
namespace Code.Server
{
public class ServerLogic : MonoBehaviour, INetEventListener
{
private NetManager _netManager;
private NetPacketProcessor _packetProcessor;
public const int MaxPlayers = 64;
private LogicTimer _logicTimer;
private readonly NetDataWriter _cachedWriter = new NetDataWriter();
private ushort _serverTick;
private ServerPlayerManager _playerManager;
private PlayerInputPacket _cachedCommand = new PlayerInputPacket();
private ServerState _serverState;
public ushort Tick => _serverTick;
public void StartServer()
{
if (_netManager.IsRunning)
return;
_netManager.Start(10515);
_logicTimer.Start();
}
private void Awake()
{
DontDestroyOnLoad(gameObject);
_logicTimer = new LogicTimer(OnLogicUpdate);
_packetProcessor = new NetPacketProcessor();
_playerManager = new ServerPlayerManager(this);
//register auto serializable vector2
_packetProcessor.RegisterNestedType((w, v) => w.Put(v), r => r.GetVector2());
//register auto serializable PlayerState
_packetProcessor.RegisterNestedType<PlayerState>();
_packetProcessor.SubscribeReusable<JoinPacket, NetPeer>(OnJoinReceived);
_netManager = new NetManager(this)
{
AutoRecycle = true
};
}
private void OnDestroy()
{
_netManager.Stop();
_logicTimer.Stop();
}
private void OnLogicUpdate()
{
_serverTick = (ushort)((_serverTick + 1) % NetworkGeneral.MaxGameSequence);
_playerManager.LogicUpdate();
if (_serverTick % 2 == 0)
{
_serverState.Tick = _serverTick;
_serverState.PlayerStates = _playerManager.PlayerStates;
int pCount = _playerManager.Count;
foreach(ServerPlayer p in _playerManager)
{
int statesMax = p.AssociatedPeer.GetMaxSinglePacketSize(DeliveryMethod.Unreliable) - ServerState.HeaderSize;
statesMax /= PlayerState.Size;
for (int s = 0; s < (pCount-1)/statesMax + 1; s++)
{
//TODO: divide
_serverState.LastProcessedCommand = p.LastProcessedCommandId;
_serverState.PlayerStatesCount = pCount;
_serverState.StartState = s * statesMax;
p.AssociatedPeer.Send(WriteSerializable(PacketType.ServerState, _serverState), DeliveryMethod.Unreliable);
}
}
}
}
private void Update()
{
_netManager.PollEvents();
_logicTimer.Update();
}
private NetDataWriter WriteSerializable<T>(PacketType type, T packet) where T : struct, INetSerializable
{
_cachedWriter.Reset();
_cachedWriter.Put((byte) type);
packet.Serialize(_cachedWriter);
return _cachedWriter;
}
private NetDataWriter WritePacket<T>(T packet) where T : class, new()
{
_cachedWriter.Reset();
_cachedWriter.Put((byte) PacketType.Serialized);
_packetProcessor.Write(_cachedWriter, packet);
return _cachedWriter;
}
private void OnJoinReceived(JoinPacket joinPacket, NetPeer peer)
{
Debug.Log("[S] Join packet received: " + joinPacket.UserName);
var player = new ServerPlayer(_playerManager, joinPacket.UserName, peer);
_playerManager.AddPlayer(player);
player.Spawn(new Vector2(Random.Range(-2f, 2f), Random.Range(-2f, 2f)));
//Send join accept
var ja = new JoinAcceptPacket { Id = player.Id, ServerTick = _serverTick };
peer.Send(WritePacket(ja), DeliveryMethod.ReliableOrdered);
//Send to old players info about new player
var pj = new PlayerJoinedPacket
{
UserName = joinPacket.UserName,
NewPlayer = true,
InitialPlayerState = player.NetworkState,
ServerTick = _serverTick
};
_netManager.SendToAll(WritePacket(pj), DeliveryMethod.ReliableOrdered, peer);
//Send to new player info about old players
pj.NewPlayer = false;
foreach(ServerPlayer otherPlayer in _playerManager)
{
if(otherPlayer == player)
continue;
pj.UserName = otherPlayer.Name;
pj.InitialPlayerState = otherPlayer.NetworkState;
peer.Send(WritePacket(pj), DeliveryMethod.ReliableOrdered);
}
}
private void OnInputReceived(NetPacketReader reader, NetPeer peer)
{
if (peer.Tag == null)
return;
_cachedCommand.Deserialize(reader);
var player = (ServerPlayer) peer.Tag;
bool antilagApplied = _playerManager.EnableAntilag(player);
player.ApplyInput(_cachedCommand, LogicTimer.FixedDelta);
if(antilagApplied)
_playerManager.DisableAntilag();
}
public void SendShoot(ref ShootPacket sp)
{
_netManager.SendToAll(WriteSerializable(PacketType.Shoot, sp), DeliveryMethod.ReliableUnordered);
}
void INetEventListener.OnPeerConnected(NetPeer peer)
{
Debug.Log("[S] Player connected: " + peer.EndPoint);
}
void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
{
Debug.Log("[S] Player disconnected: " + disconnectInfo.Reason);
if (peer.Tag != null)
{
byte playerId = (byte)peer.Id;
if (_playerManager.RemovePlayer(playerId))
{
var plp = new PlayerLeavedPacket { Id = (byte)peer.Id };
_netManager.SendToAll(WritePacket(plp), DeliveryMethod.ReliableOrdered);
}
}
}
void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError socketError)
{
Debug.Log("[S] NetworkError: " + socketError);
}
void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod)
{
byte packetType = reader.GetByte();
if (packetType >= NetworkGeneral.PacketTypesCount)
return;
PacketType pt = (PacketType) packetType;
switch (pt)
{
case PacketType.Movement:
OnInputReceived(reader, peer);
break;
case PacketType.Serialized:
_packetProcessor.ReadAllPackets(reader, peer);
break;
default:
Debug.Log("Unhandled packet: " + pt);
break;
}
}
void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader,
UnconnectedMessageType messageType)
{
}
void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency)
{
if (peer.Tag != null)
{
var p = (ServerPlayer) peer.Tag;
p.Ping = latency;
}
}
void INetEventListener.OnConnectionRequest(ConnectionRequest request)
{
request.AcceptIfKey("ExampleGame");
}
}
}
================================================
FILE: Assets/Code/Server/ServerLogic.cs.meta
================================================
fileFormatVersion: 2
guid: 1e51c98f0b54146429c775c426760c8a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Code/Server/ServerPlayer.cs
================================================
using Code.Shared;
using LiteNetLib;
using UnityEngine;
namespace Code.Server
{
public class ServerPlayer : BasePlayer
{
private readonly ServerPlayerManager _playerManager;
public readonly NetPeer AssociatedPeer;
public PlayerState NetworkState;
public ushort LastProcessedCommandId { get; private set; }
public ServerPlayer(ServerPlayerManager playerManager, string name, NetPeer peer) : base(playerManager, name, (byte)peer.Id)
{
_playerManager = playerManager;
peer.Tag = this;
AssociatedPeer = peer;
NetworkState = new PlayerState {Id = (byte) peer.Id};
}
public override void ApplyInput(PlayerInputPacket command, float delta)
{
if (NetworkGeneral.SeqDiff(command.Id, LastProcessedCommandId) <= 0)
return;
LastProcessedCommandId = command.Id;
base.ApplyInput(command, delta);
}
public override void Update(float delta)
{
base.Update(delta);
NetworkState.Position = _position;
NetworkState.Rotation = _rotation;
NetworkState.Tick = LastProcessedCommandId;
//Draw cross as server player
const float sz = 0.1f;
Debug.DrawLine(
new Vector2(Position.x - sz, Position.y ),
new Vector2(Position.x + sz, Position.y ),
Color.white);
Debug.DrawLine(
new Vector2(Position.x, Position.y - sz ),
new Vector2(Position.x, Position.y + sz ),
Color.white);
}
}
}
================================================
FILE: Assets/Code/Server/ServerPlayer.cs.meta
================================================
fileFormatVersion: 2
guid: 8ad17e029d4b43eeaedf4a29939994e3
timeCreated: 1552515641
================================================
FILE: Assets/Code/Server/ServerPlayerManager.cs
================================================
using System.Collections.Generic;
using Code.Shared;
using LiteNetLib;
using UnityEngine;
namespace Code.Server
{
public class ServerPlayerManager : BasePlayerManager
{
private readonly ServerLogic _serverLogic;
private readonly ServerPlayer[] _players;
private readonly AntilagSystem _antilagSystem;
public readonly PlayerState[] PlayerStates;
private int _playersCount;
public override int Count => _playersCount;
public ServerPlayerManager(ServerLogic serverLogic)
{
_serverLogic = serverLogic;
_antilagSystem = new AntilagSystem(60, ServerLogic.MaxPlayers);
_players = new ServerPlayer[ServerLogic.MaxPlayers];
PlayerStates = new PlayerState[ServerLogic.MaxPlayers];
}
public bool EnableAntilag(ServerPlayer forPlayer)
{
return _antilagSystem.TryApplyAntilag(_players, _serverLogic.Tick, forPlayer.AssociatedPeer.Id);
}
public void DisableAntilag()
{
_antilagSystem.RevertAntilag(_players);
}
public override IEnumerator<BasePlayer> GetEnumerator()
{
int i = 0;
while (i < _playersCount)
{
yield return _players[i];
i++;
}
}
public override void OnShoot(BasePlayer from, Vector2 to, BasePlayer hit)
{
var serverPlayer = (ServerPlayer) from;
ShootPacket sp = new ShootPacket
{
FromPlayer = serverPlayer.Id,
CommandId = serverPlayer.LastProcessedCommandId,
ServerTick = _serverLogic.Tick,
Hit = to
};
_serverLogic.SendShoot(ref sp);
}
public void AddPlayer(ServerPlayer player)
{
for (int i = 0; i < _playersCount; i++)
{
if (_players[i].Id == player.Id)
{
_players[i] = player;
return;
}
}
_players[_playersCount] = player;
_playersCount++;
}
public override void LogicUpdate()
{
for (int i = 0; i < _playersCount; i++)
{
var p = _players[i];
p.Update(LogicTimer.FixedDelta);
PlayerStates[i] = p.NetworkState;
}
}
public bool RemovePlayer(byte playerId)
{
for (int i = 0; i < _playersCount; i++)
{
if (_players[i].Id == playerId)
{
_playersCount--;
_players[i] = _players[_playersCount];
_players[_playersCount] = null;
return true;
}
}
return false;
}
}
}
================================================
FILE: Assets/Code/Server/ServerPlayerManager.cs.meta
================================================
fileFormatVersion: 2
guid: a4f821c063aa411fa470499231c8553a
timeCreated: 1553431094
================================================
FILE: Assets/Code/Server.meta
================================================
fileFormatVersion: 2
guid: 26e8c150dc35a224e965b8abec2e0cfc
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Code/Shared/BasePlayer.cs
================================================
using UnityEngine;
namespace Code.Shared
{
public abstract class BasePlayer
{
public readonly string Name;
private float _speed = 3f;
private GameTimer _shootTimer = new GameTimer(0.2f);
private BasePlayerManager _playerManager;
protected Vector2 _position;
protected float _rotation;
protected byte _health;
public const float Radius = 0.5f;
public bool IsAlive => _health > 0;
public byte Health => _health;
public Vector2 Position => _position;
public float Rotation => _rotation;
public readonly byte Id;
public int Ping;
protected BasePlayer(BasePlayerManager playerManager, string name, byte id)
{
Id = id;
Name = name;
_playerManager = playerManager;
}
public virtual void Spawn(Vector2 position)
{
_position = position;
_rotation = 0;
_health = 100;
}
private void Shoot()
{
const float MaxLength = 20f;
Vector2 dir = new Vector2(Mathf.Cos(_rotation), Mathf.Sin(_rotation));
var player = _playerManager.CastToPlayer(_position, dir, MaxLength, this);
Vector2 target = _position + dir * (player != null ? Vector2.Distance(_position, player._position) : MaxLength);
_playerManager.OnShoot(this, target, player);
}
public virtual void ApplyInput(PlayerInputPacket command, float delta)
{
Vector2 velocity = Vector2.zero;
if ((command.Keys & MovementKeys.Up) != 0)
velocity.y = -1f;
if ((command.Keys & MovementKeys.Down) != 0)
velocity.y = 1f;
if ((command.Keys & MovementKeys.Left) != 0)
velocity.x = -1f;
if ((command.Keys & MovementKeys.Right) != 0)
velocity.x = 1f;
_position += velocity.normalized * _speed * delta;
_rotation = command.Rotation;
if ((command.Keys & MovementKeys.Fire) != 0)
{
if (_shootTimer.IsTimeElapsed)
{
_shootTimer.Reset();
Shoot();
}
}
}
public virtual void Update(float delta)
{
_shootTimer.UpdateAsCooldown(delta);
}
}
}
================================================
FILE: Assets/Code/Shared/BasePlayer.cs.meta
================================================
fileFormatVersion: 2
guid: 0b3166ab83ce8bc42995be041437971b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Code/Shared/BasePlayerManager.cs
================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Code.Shared
{
public abstract class BasePlayerManager : IEnumerable<BasePlayer>
{
public abstract IEnumerator<BasePlayer> GetEnumerator();
public abstract int Count { get; }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public BasePlayer CastToPlayer(Vector2 from, Vector2 dir, float length, BasePlayer exclude)
{
BasePlayer result = null;
Vector2 target = from + dir * length;
foreach(var p in this)
{
if(p == exclude)
continue;
if (Collisions.CheckIntersection(from.x, from.y, target.x, target.y, p))
{
//TODO: check near
if(result == null)
result = p;
}
}
return result;
}
public abstract void LogicUpdate();
public abstract void OnShoot(BasePlayer from, Vector2 to, BasePlayer hit);
}
}
================================================
FILE: Assets/Code/Shared/BasePlayerManager.cs.meta
================================================
fileFormatVersion: 2
guid: 464641a9645748548b39dcb0afed1fd4
timeCreated: 1553430803
================================================
FILE: Assets/Code/Shared/Collisions.cs
================================================
namespace Code.Shared
{
public static class Collisions
{
public static bool CheckIntersection(float x1, float y1, float x2, float y2, BasePlayer player)
{
float cx = player.Position.x;
float cy = player.Position.y;
float distX = x2-x1;
float distY = y2-y1;
float lineLenSqr = distX * distX + distY * distY;
float dot = ( (cx-x1)*distX + (cy-y1)*distY ) / lineLenSqr;
float closestX = x1 + dot * distX;
float closestY = y1 + dot * distY;
float dcx1 = closestX - x1;
float dcy1 = closestY - y1;
float dcx2 = closestX - x2;
float dcy2 = closestY - y2;
float distToLineSqr1 = dcx1 * dcx1 + dcy1 * dcy1;
float distToLineSqr2 = dcx2 * dcx2 + dcy2 * dcy2;
if (distToLineSqr1 > lineLenSqr || distToLineSqr2 > lineLenSqr)
return false;
distX = closestX - cx;
distY = closestY - cy;
return distX*distX + distY*distY <= BasePlayer.Radius * BasePlayer.Radius;
}
}
}
================================================
FILE: Assets/Code/Shared/Collisions.cs.meta
================================================
fileFormatVersion: 2
guid: 22917542b6524d9085c4f7323d79e532
timeCreated: 1553428656
================================================
FILE: Assets/Code/Shared/Extensions.cs
================================================
using LiteNetLib.Utils;
using UnityEngine;
namespace Code.Shared
{
public static class Extensions
{
public static void Put(this NetDataWriter writer, Vector2 vector)
{
writer.Put(vector.x);
writer.Put(vector.y);
}
public static Vector2 GetVector2(this NetDataReader reader)
{
Vector2 v;
v.x = reader.GetFloat();
v.y = reader.GetFloat();
return v;
}
public static T GetRandomElement<T>(this T[] array)
{
return array[Random.Range(0, array.Length)];
}
}
}
================================================
FILE: Assets/Code/Shared/Extensions.cs.meta
================================================
fileFormatVersion: 2
guid: 774af25bfc0f472287bc2812673fa9d0
timeCreated: 1552513976
================================================
FILE: Assets/Code/Shared/GamePackets.cs
================================================
using System;
using LiteNetLib.Utils;
using UnityEngine;
namespace Code.Shared
{
public enum PacketType : byte
{
Movement,
Spawn,
ServerState,
Serialized,
Shoot
}
//Auto serializable packets
public class JoinPacket
{
public string UserName { get; set; }
}
public class JoinAcceptPacket
{
public byte Id { get; set; }
public ushort ServerTick { get; set; }
}
public class PlayerJoinedPacket
{
public string UserName { get; set; }
public bool NewPlayer { get; set; }
public byte Health { get; set; }
public ushort ServerTick { get; set; }
public PlayerState InitialPlayerState { get; set; }
}
public class PlayerLeavedPacket
{
public byte Id { get; set; }
}
//Manual serializable packets
public struct SpawnPacket : INetSerializable
{
public long PlayerId;
public Vector2 Position;
public void Serialize(NetDataWriter writer)
{
writer.Put(PlayerId);
writer.Put(Position);
}
public void Deserialize(NetDataReader reader)
{
PlayerId = reader.GetLong();
Position = reader.GetVector2();
}
}
[Flags]
public enum MovementKeys : byte
{
Left = 1 << 1,
Right = 1 << 2,
Up = 1 << 3,
Down = 1 << 4,
Fire = 1 << 5
}
public struct ShootPacket : INetSerializable
{
public byte FromPlayer;
public ushort CommandId;
public Vector2 Hit;
public ushort ServerTick;
public void Serialize(NetDataWriter writer)
{
writer.Put(FromPlayer);
writer.Put(CommandId);
writer.Put(Hit);
writer.Put(ServerTick);
}
public void Deserialize(NetDataReader reader)
{
FromPlayer = reader.GetByte();
CommandId = reader.GetUShort();
Hit = reader.GetVector2();
ServerTick = reader.GetUShort();
}
}
public struct PlayerInputPacket : INetSerializable
{
public ushort Id;
public MovementKeys Keys;
public float Rotation;
public ushort ServerTick;
public void Serialize(NetDataWriter writer)
{
writer.Put(Id);
writer.Put((byte)Keys);
writer.Put(Rotation);
writer.Put(ServerTick);
}
public void Deserialize(NetDataReader reader)
{
Id = reader.GetUShort();
Keys = (MovementKeys)reader.GetByte();
Rotation = reader.GetFloat();
ServerTick = reader.GetUShort();
}
}
public struct PlayerState : INetSerializable
{
public byte Id;
public Vector2 Position;
public float Rotation;
public ushort Tick;
public const int Size = 1 + 8 + 4 + 2;
public void Serialize(NetDataWriter writer)
{
writer.Put(Id);
writer.Put(Position);
writer.Put(Rotation);
writer.Put(Tick);
}
public void Deserialize(NetDataReader reader)
{
Id = reader.GetByte();
Position = reader.GetVector2();
Rotation = reader.GetFloat();
Tick = reader.GetUShort();
}
}
public struct ServerState : INetSerializable
{
public ushort Tick;
public ushort LastProcessedCommand;
public int PlayerStatesCount;
public int StartState; //server only
public PlayerState[] PlayerStates;
//tick
public const int HeaderSize = sizeof(ushort)*2;
public void Serialize(NetDataWriter writer)
{
writer.Put(Tick);
writer.Put(LastProcessedCommand);
for (int i = 0; i < PlayerStatesCount; i++)
PlayerStates[StartState + i].Serialize(writer);
}
public void Deserialize(NetDataReader reader)
{
Tick = reader.GetUShort();
LastProcessedCommand = reader.GetUShort();
PlayerStatesCount = reader.AvailableBytes / PlayerState.Size;
if (PlayerStates == null || PlayerStates.Length < PlayerStatesCount)
PlayerStates = new PlayerState[PlayerStatesCount];
for (int i = 0; i < PlayerStatesCount; i++)
PlayerStates[i].Deserialize(reader);
}
}
}
================================================
FILE: Assets/Code/Shared/GamePackets.cs.meta
================================================
fileFormatVersion: 2
guid: ea1f70e104cd418e8d5e6dc52b99ffb5
timeCreated: 1552514144
================================================
FILE: Assets/Code/Shared/GamePool.cs
================================================
using System;
namespace Code.Shared
{
public class GamePool<T> where T : class
{
private readonly T[] _pool;
private readonly Func<T> _creator;
private int _count;
public GamePool(Func<T> creator) : this(creator, 8)
{
}
public GamePool(Func<T> creator, int capacity)
{
_pool = new T[capacity];
_creator = creator;
}
public T Get()
{
if (_count > 0)
{
_count--;
var result = _pool[_count];
_pool[_count] = default;
return result;
}
return _creator();
}
public void Put(T gameObject)
{
_pool[_count] = gameObject;
_count++;
}
}
}
================================================
FILE: Assets/Code/Shared/GamePool.cs.meta
================================================
fileFormatVersion: 2
guid: 26c97d2cfdfd4ba48e7b065fd13e9c6b
timeCreated: 1553454288
================================================
FILE: Assets/Code/Shared/GameTimer.cs
================================================
using System;
namespace Code.Shared
{
public struct GameTimer
{
private float _maxTime;
private float _time;
public bool IsTimeElapsed => _time >= _maxTime;
public float Time => _time;
public float MaxTime
{
get => _maxTime;
set => _maxTime = value;
}
public GameTimer(float maxTime)
{
_maxTime = maxTime;
_time = 0f;
}
public void Reset()
{
_time = 0f;
}
public void UpdateAsCooldown(float delta)
{
_time += delta;
}
public void Update(float delta, Action onUpdate)
{
_time += delta;
while (_time >= _maxTime)
{
_time -= _maxTime;
onUpdate();
}
}
}
}
================================================
FILE: Assets/Code/Shared/GameTimer.cs.meta
================================================
fileFormatVersion: 2
guid: d0c4fc1f8e504c7f910bd163300866e8
timeCreated: 1553426365
================================================
FILE: Assets/Code/Shared/LiteRingBuffer.cs
================================================
using System;
using System.Collections;
using System.Collections.Generic;
namespace Code.Shared
{
public class LiteRingBuffer<T> : IEnumerable<T>
{
private readonly T[] _elements;
private int _start;
private int _end;
private int _count;
private readonly int _capacity;
public T this[int i] => _elements[(_start + i) % _capacity];
public LiteRingBuffer(int count)
{
_elements = new T[count];
_capacity = count;
}
public void Add(T element)
{
if(_count == _capacity)
throw new ArgumentException();
_elements[_end] = element;
_end = (_end + 1) % _capacity;
_count++;
}
public void FastClear()
{
_start = 0;
_end = 0;
_count = 0;
}
public int Count => _count;
public T First => _elements[_start];
public T Last => _elements[(_start+_count-1)%_capacity];
public bool IsFull => _count == _capacity;
public void RemoveFromStart(int count)
{
if(count > _capacity || count > _count)
throw new ArgumentException();
_start = (_start + count) % _capacity;
_count -= count;
}
public IEnumerator<T> GetEnumerator()
{
int counter = _start;
while (counter != _end)
{
yield return _elements[counter];
counter = (counter + 1) % _capacity;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
================================================
FILE: Assets/Code/Shared/LiteRingBuffer.cs.meta
================================================
fileFormatVersion: 2
guid: de5c9b10e72c4672ad210ea9f2a7ccad
timeCreated: 1553348923
================================================
FILE: Assets/Code/Shared/LogicTimer.cs
================================================
using System;
using System.Diagnostics;
namespace Code.Shared
{
public class LogicTimer
{
public const float FramesPerSecond = 30.0f;
public const float FixedDelta = 1.0f / FramesPerSecond;
private double _accumulator;
private long _lastTime;
private readonly Stopwatch _stopwatch;
private readonly Action _action;
public float LerpAlpha => (float)_accumulator/FixedDelta;
public LogicTimer(Action action)
{
_stopwatch = new Stopwatch();
_action = action;
}
public void Start()
{
_lastTime = 0;
_accumulator = 0.0;
_stopwatch.Restart();
}
public void Stop()
{
_stopwatch.Stop();
}
public void Update()
{
long elapsedTicks = _stopwatch.ElapsedTicks;
_accumulator += (double)(elapsedTicks - _lastTime)/Stopwatch.Frequency;
_lastTime = elapsedTicks;
while (_accumulator >= FixedDelta)
{
_action();
_accumulator -= FixedDelta;
}
}
}
}
================================================
FILE: Assets/Code/Shared/LogicTimer.cs.meta
================================================
fileFormatVersion: 2
guid: c2cf8177f8ed49a4badb018a3dc7c710
timeCreated: 1552521012
================================================
FILE: Assets/Code/Shared/NetworkGeneral.cs
================================================
using System;
namespace Code.Shared
{
public static class NetworkGeneral
{
public const int ProtocolId = 1;
public static readonly int PacketTypesCount = Enum.GetValues(typeof(PacketType)).Length;
public const int MaxGameSequence = 1024;
public const int HalfMaxGameSequence = MaxGameSequence / 2;
public static int SeqDiff(int a, int b)
{
return Diff(a, b, HalfMaxGameSequence);
}
public static int Diff(int a, int b, int halfMax)
{
return (a - b + halfMax*3) % (halfMax*2) - halfMax;
}
}
}
================================================
FILE: Assets/Code/Shared/NetworkGeneral.cs.meta
================================================
fileFormatVersion: 2
guid: b8a3ef5ee59f4b75ae44ec2e14551cc7
timeCreated: 1552514562
================================================
FILE: Assets/Code/Shared.meta
================================================
fileFormatVersion: 2
guid: 5b5e02f68e288b14ba1ca61ba84a6e1b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Code.meta
================================================
fileFormatVersion: 2
guid: 0d17f5c4499ee5c4498aa660551e4658
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Materials/ShootEffectMat.mat
================================================
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: ShootEffectMat
m_Shader: {fileID: 211, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords: _ALPHABLEND_ON _COLORCOLOR_ON
m_LightmapFlags: 0
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
disabledShaderPasses:
- ALWAYS
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _AlphaTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- PixelSnap: 0
- _BlendOp: 0
- _BumpScale: 1
- _CameraFadingEnabled: 0
- _CameraFarFadeDistance: 2
- _CameraNearFadeDistance: 1
- _ColorMode: 4
- _Cull: 2
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DistortionBlend: 0.5
- _DistortionEnabled: 0
- _DistortionStrength: 1
- _DistortionStrengthScaled: 0
- _DstBlend: 1
- _EmissionEnabled: 0
- _EnableExternalAlpha: 0
- _FlipbookMode: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _LightingEnabled: 0
- _Metallic: 0
- _Mode: 4
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SoftParticlesEnabled: 0
- _SoftParticlesFarFadeDistance: 1
- _SoftParticlesNearFadeDistance: 0
- _SpecularHighlights: 1
- _SrcBlend: 5
- _UVSec: 0
- _ZWrite: 0
m_Colors:
- _CameraFadeParams: {r: 0, g: Infinity, b: 0, a: 0}
- _Color: {r: 1, g: 0.9798179, b: 0, a: 1}
- _ColorAddSubDiff: {r: 0, g: 0, b: 0, a: 0}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _Flip: {r: 1, g: 1, b: 1, a: 1}
- _RendererColor: {r: 1, g: 1, b: 1, a: 1}
- _SoftParticleFadeParams: {r: 0, g: 0, b: 0, a: 0}
================================================
FILE: Assets/Materials/ShootEffectMat.mat.meta
================================================
fileFormatVersion: 2
guid: 1d13efa0bfe6559499d9e8d00237ef50
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Materials.meta
================================================
fileFormatVersion: 2
guid: e409e904533a1fc46928119b0f513138
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/BaseChannel.cs
================================================
using System.Collections.Generic;
namespace LiteNetLib
{
internal abstract class BaseChannel
{
public BaseChannel Next;
protected readonly NetPeer Peer;
protected readonly Queue<NetPacket> OutgoingQueue;
protected BaseChannel(NetPeer peer)
{
Peer = peer;
OutgoingQueue = new Queue<NetPacket>(64);
}
public int PacketsInQueue
{
get { return OutgoingQueue.Count; }
}
public void AddToQueue(NetPacket packet)
{
lock (OutgoingQueue)
OutgoingQueue.Enqueue(packet);
}
public abstract void SendNextPackets();
public abstract bool ProcessPacket(NetPacket packet);
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/BaseChannel.cs.meta
================================================
fileFormatVersion: 2
guid: 507b99235e7d3fe4387f5cbbc92f03ba
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/ConnectionRequest.cs
================================================
using System.Net;
using System.Threading;
using LiteNetLib.Utils;
namespace LiteNetLib
{
internal enum ConnectionRequestResult
{
None,
Accept,
Reject,
RejectForce
}
public class ConnectionRequest
{
private readonly NetManager _listener;
private int _used;
public readonly NetDataReader Data;
internal ConnectionRequestResult Result { get; private set; }
internal long ConnectionTime;
internal byte ConnectionNumber;
public readonly IPEndPoint RemoteEndPoint;
private bool TryActivate()
{
return Interlocked.CompareExchange(ref _used, 1, 0) == 0;
}
internal void UpdateRequest(NetConnectRequestPacket connRequest)
{
if (connRequest.ConnectionTime >= ConnectionTime)
{
ConnectionTime = connRequest.ConnectionTime;
ConnectionNumber = connRequest.ConnectionNumber;
}
}
internal ConnectionRequest(
long connectionId,
byte connectionNumber,
NetDataReader netDataReader,
IPEndPoint endPoint,
NetManager listener)
{
ConnectionTime = connectionId;
ConnectionNumber = connectionNumber;
RemoteEndPoint = endPoint;
Data = netDataReader;
_listener = listener;
}
public NetPeer AcceptIfKey(string key)
{
if (!TryActivate())
return null;
try
{
if (Data.GetString() == key)
Result = ConnectionRequestResult.Accept;
}
catch
{
NetDebug.WriteError("[AC] Invalid incoming data");
}
if (Result == ConnectionRequestResult.Accept)
return _listener.OnConnectionSolved(this, null, 0, 0);
Result = ConnectionRequestResult.Reject;
_listener.OnConnectionSolved(this, null, 0, 0);
return null;
}
/// <summary>
/// Accept connection and get new NetPeer as result
/// </summary>
/// <returns>Connected NetPeer</returns>
public NetPeer Accept()
{
if (!TryActivate())
return null;
Result = ConnectionRequestResult.Accept;
return _listener.OnConnectionSolved(this, null, 0, 0);
}
public void Reject(byte[] rejectData, int start, int length, bool force)
{
if (!TryActivate())
return;
Result = force ? ConnectionRequestResult.RejectForce : ConnectionRequestResult.Reject;
_listener.OnConnectionSolved(this, rejectData, start, length);
}
public void Reject(byte[] rejectData, int start, int length)
{
Reject(rejectData, start, length, false);
}
public void RejectForce(byte[] rejectData, int start, int length)
{
Reject(rejectData, start, length, true);
}
public void RejectForce()
{
Reject(null, 0, 0, true);
}
public void RejectForce(byte[] rejectData)
{
Reject(rejectData, 0, rejectData.Length, true);
}
public void RejectForce(NetDataWriter rejectData)
{
Reject(rejectData.Data, 0, rejectData.Length, true);
}
public void Reject()
{
Reject(null, 0, 0, false);
}
public void Reject(byte[] rejectData)
{
Reject(rejectData, 0, rejectData.Length, false);
}
public void Reject(NetDataWriter rejectData)
{
Reject(rejectData.Data, 0, rejectData.Length, false);
}
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/ConnectionRequest.cs.meta
================================================
fileFormatVersion: 2
guid: c7f36a00f0b4511498133b6c3c893427
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/INetEventListener.cs
================================================
using System.Net;
using System.Net.Sockets;
namespace LiteNetLib
{
/// <summary>
/// Type of message that you receive in OnNetworkReceiveUnconnected event
/// </summary>
public enum UnconnectedMessageType
{
BasicMessage,
Broadcast
}
/// <summary>
/// Disconnect reason that you receive in OnPeerDisconnected event
/// </summary>
public enum DisconnectReason
{
ConnectionFailed,
Timeout,
HostUnreachable,
NetworkUnreachable,
RemoteConnectionClose,
DisconnectPeerCalled,
ConnectionRejected,
InvalidProtocol,
UnknownHost,
Reconnect,
PeerToPeerConnection
}
/// <summary>
/// Additional information about disconnection
/// </summary>
public struct DisconnectInfo
{
/// <summary>
/// Additional info why peer disconnected
/// </summary>
public DisconnectReason Reason;
/// <summary>
/// Error code (if reason is SocketSendError or SocketReceiveError)
/// </summary>
public SocketError SocketErrorCode;
/// <summary>
/// Additional data that can be accessed (only if reason is RemoteConnectionClose)
/// </summary>
public NetPacketReader AdditionalData;
}
public interface INetEventListener
{
/// <summary>
/// New remote peer connected to host, or client connected to remote host
/// </summary>
/// <param name="peer">Connected peer object</param>
void OnPeerConnected(NetPeer peer);
/// <summary>
/// Peer disconnected
/// </summary>
/// <param name="peer">disconnected peer</param>
/// <param name="disconnectInfo">additional info about reason, errorCode or data received with disconnect message</param>
void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo);
/// <summary>
/// Network error (on send or receive)
/// </summary>
/// <param name="endPoint">From endPoint (can be null)</param>
/// <param name="socketError">Socket error</param>
void OnNetworkError(IPEndPoint endPoint, SocketError socketError);
/// <summary>
/// Received some data
/// </summary>
/// <param name="peer">From peer</param>
/// <param name="reader">DataReader containing all received data</param>
/// <param name="deliveryMethod">Type of received packet</param>
void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod);
/// <summary>
/// Received unconnected message
/// </summary>
/// <param name="remoteEndPoint">From address (IP and Port)</param>
/// <param name="reader">Message data</param>
/// <param name="messageType">Message type (simple, discovery request or response)</param>
void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType);
/// <summary>
/// Latency information updated
/// </summary>
/// <param name="peer">Peer with updated latency</param>
/// <param name="latency">latency value in milliseconds</param>
void OnNetworkLatencyUpdate(NetPeer peer, int latency);
/// <summary>
/// On peer connection requested
/// </summary>
/// <param name="request">Request information (EndPoint, internal id, additional data)</param>
void OnConnectionRequest(ConnectionRequest request);
}
public interface IDeliveryEventListener
{
/// <summary>
/// On reliable message delivered
/// </summary>
/// <param name="peer"></param>
/// <param name="userData"></param>
void OnMessageDelivered(NetPeer peer, object userData);
}
public class EventBasedNetListener : INetEventListener, IDeliveryEventListener
{
public delegate void OnPeerConnected(NetPeer peer);
public delegate void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo);
public delegate void OnNetworkError(IPEndPoint endPoint, SocketError socketError);
public delegate void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod);
public delegate void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType);
public delegate void OnNetworkLatencyUpdate(NetPeer peer, int latency);
public delegate void OnConnectionRequest(ConnectionRequest request);
public delegate void OnDeliveryEvent(NetPeer peer, object userData);
public event OnPeerConnected PeerConnectedEvent;
public event OnPeerDisconnected PeerDisconnectedEvent;
public event OnNetworkError NetworkErrorEvent;
public event OnNetworkReceive NetworkReceiveEvent;
public event OnNetworkReceiveUnconnected NetworkReceiveUnconnectedEvent;
public event OnNetworkLatencyUpdate NetworkLatencyUpdateEvent;
public event OnConnectionRequest ConnectionRequestEvent;
public event OnDeliveryEvent DeliveryEvent;
public void ClearPeerConnectedEvent()
{
PeerConnectedEvent = null;
}
public void ClearPeerDisconnectedEvent()
{
PeerDisconnectedEvent = null;
}
public void ClearNetworkErrorEvent()
{
NetworkErrorEvent = null;
}
public void ClearNetworkReceiveEvent()
{
NetworkReceiveEvent = null;
}
public void ClearNetworkReceiveUnconnectedEvent()
{
NetworkReceiveUnconnectedEvent = null;
}
public void ClearNetworkLatencyUpdateEvent()
{
NetworkLatencyUpdateEvent = null;
}
public void ClearConnectionRequestEvent()
{
ConnectionRequestEvent = null;
}
public void ClearDeliveryEvent()
{
DeliveryEvent = null;
}
void INetEventListener.OnPeerConnected(NetPeer peer)
{
if (PeerConnectedEvent != null)
PeerConnectedEvent(peer);
}
void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
{
if (PeerDisconnectedEvent != null)
PeerDisconnectedEvent(peer, disconnectInfo);
}
void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError socketErrorCode)
{
if (NetworkErrorEvent != null)
NetworkErrorEvent(endPoint, socketErrorCode);
}
void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod)
{
if (NetworkReceiveEvent != null)
NetworkReceiveEvent(peer, reader, deliveryMethod);
}
void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType)
{
if (NetworkReceiveUnconnectedEvent != null)
NetworkReceiveUnconnectedEvent(remoteEndPoint, reader, messageType);
}
void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency)
{
if (NetworkLatencyUpdateEvent != null)
NetworkLatencyUpdateEvent(peer, latency);
}
void INetEventListener.OnConnectionRequest(ConnectionRequest request)
{
if (ConnectionRequestEvent != null)
ConnectionRequestEvent(request);
}
void IDeliveryEventListener.OnMessageDelivered(NetPeer peer, object userData)
{
if (DeliveryEvent != null)
DeliveryEvent(peer, userData);
}
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/INetEventListener.cs.meta
================================================
fileFormatVersion: 2
guid: 1ad7743bbac7af64e930fcae94fd1a7d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/Layers/Crc32cLayer.cs
================================================
using LiteNetLib.Utils;
using System;
using System.Net;
namespace LiteNetLib.Layers
{
public sealed class Crc32cLayer : PacketLayerBase
{
public Crc32cLayer() : base(CRC32C.ChecksumSize)
{
}
public override void ProcessInboundPacket(IPEndPoint endPoint, ref byte[] data, ref int offset, ref int length)
{
if (length < NetConstants.HeaderSize + CRC32C.ChecksumSize)
{
NetDebug.WriteError("[NM] DataReceived size: bad!");
return;
}
int checksumPoint = length - CRC32C.ChecksumSize;
if (CRC32C.Compute(data, offset, checksumPoint) != BitConverter.ToUInt32(data, checksumPoint))
{
NetDebug.Write("[NM] DataReceived checksum: bad!");
return;
}
length -= CRC32C.ChecksumSize;
}
public override void ProcessOutBoundPacket(IPEndPoint endPoint, ref byte[] data, ref int offset, ref int length)
{
FastBitConverter.GetBytes(data, length, CRC32C.Compute(data, offset, length));
length += CRC32C.ChecksumSize;
}
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/Layers/Crc32cLayer.cs.meta
================================================
fileFormatVersion: 2
guid: 85b0c9ac1a5bf284082c22f13da241e4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/Layers/PacketLayerBase.cs
================================================
using System.Net;
namespace LiteNetLib.Layers
{
public abstract class PacketLayerBase
{
public readonly int ExtraPacketSizeForLayer;
protected PacketLayerBase(int extraPacketSizeForLayer)
{
ExtraPacketSizeForLayer = extraPacketSizeForLayer;
}
public abstract void ProcessInboundPacket(IPEndPoint endPoint, ref byte[] data, ref int offset, ref int length);
public abstract void ProcessOutBoundPacket(IPEndPoint endPoint, ref byte[] data, ref int offset, ref int length);
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/Layers/PacketLayerBase.cs.meta
================================================
fileFormatVersion: 2
guid: bf2e5160bd776544693c1c289882a126
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/Layers/XorEncryptLayer.cs
================================================
using System;
using System.Net;
using System.Text;
namespace LiteNetLib.Layers
{
public class XorEncryptLayer : PacketLayerBase
{
private byte[] _byteKey;
public XorEncryptLayer() : base(0)
{
}
public XorEncryptLayer(byte[] key) : this()
{
SetKey(key);
}
public XorEncryptLayer(string key) : this()
{
SetKey(key);
}
public void SetKey(string key)
{
_byteKey = Encoding.UTF8.GetBytes(key);
}
public void SetKey(byte[] key)
{
if (_byteKey == null || _byteKey.Length != key.Length)
_byteKey = new byte[key.Length];
Buffer.BlockCopy(key, 0, _byteKey, 0, key.Length);
}
public override void ProcessInboundPacket(IPEndPoint endPoint, ref byte[] data, ref int offset, ref int length)
{
if (_byteKey == null)
return;
var cur = offset;
for (var i = 0; i < length; i++, cur++)
{
data[cur] = (byte)(data[cur] ^ _byteKey[i % _byteKey.Length]);
}
}
public override void ProcessOutBoundPacket(IPEndPoint endPoint, ref byte[] data, ref int offset, ref int length)
{
if (_byteKey == null)
return;
var cur = offset;
for (var i = 0; i < length; i++, cur++)
{
data[cur] = (byte)(data[cur] ^ _byteKey[i % _byteKey.Length]);
}
}
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/Layers/XorEncryptLayer.cs.meta
================================================
fileFormatVersion: 2
guid: 10422bff1ab7eb04894100d55d899764
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/Layers.meta
================================================
fileFormatVersion: 2
guid: 370c4c298d0daf74781d2b0aa5420b81
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/NatPunchModule.cs
================================================
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using LiteNetLib.Utils;
namespace LiteNetLib
{
public enum NatAddressType
{
Internal,
External
}
public interface INatPunchListener
{
void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token);
void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token);
}
public class EventBasedNatPunchListener : INatPunchListener
{
public delegate void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token);
public delegate void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token);
public event OnNatIntroductionRequest NatIntroductionRequest;
public event OnNatIntroductionSuccess NatIntroductionSuccess;
void INatPunchListener.OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token)
{
if(NatIntroductionRequest != null)
NatIntroductionRequest(localEndPoint, remoteEndPoint, token);
}
void INatPunchListener.OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token)
{
if (NatIntroductionSuccess != null)
NatIntroductionSuccess(targetEndPoint, type, token);
}
}
/// <summary>
/// Module for UDP NAT Hole punching operations. Can be accessed from NetManager
/// </summary>
public sealed class NatPunchModule
{
struct RequestEventData
{
public IPEndPoint LocalEndPoint;
public IPEndPoint RemoteEndPoint;
public string Token;
}
struct SuccessEventData
{
public IPEndPoint TargetEndPoint;
public NatAddressType Type;
public string Token;
}
class NatIntroduceRequestPacket
{
public IPEndPoint Internal { get; set; }
public string Token { get; set; }
}
class NatIntroduceResponsePacket
{
public IPEndPoint Internal { get; set; }
public IPEndPoint External { get; set; }
public string Token { get; set; }
}
class NatPunchPacket
{
public string Token { get; set; }
public bool IsExternal { get; set; }
}
private readonly NetSocket _socket;
private readonly Queue<RequestEventData> _requestEvents = new Queue<RequestEventData>();
private readonly Queue<SuccessEventData> _successEvents = new Queue<SuccessEventData>();
private readonly NetDataReader _cacheReader = new NetDataReader();
private readonly NetDataWriter _cacheWriter = new NetDataWriter();
private readonly NetPacketProcessor _netPacketProcessor = new NetPacketProcessor(MaxTokenLength);
private INatPunchListener _natPunchListener;
public const int MaxTokenLength = 256;
internal NatPunchModule(NetSocket socket)
{
_socket = socket;
_netPacketProcessor.SubscribeReusable<NatIntroduceResponsePacket>(OnNatIntroductionResponse);
_netPacketProcessor.SubscribeReusable<NatIntroduceRequestPacket, IPEndPoint>(OnNatIntroductionRequest);
_netPacketProcessor.SubscribeReusable<NatPunchPacket, IPEndPoint>(OnNatPunch);
}
internal void ProcessMessage(IPEndPoint senderEndPoint, NetPacket packet)
{
lock (_cacheReader)
{
_cacheReader.SetSource(packet.RawData, NetConstants.HeaderSize, packet.Size);
_netPacketProcessor.ReadAllPackets(_cacheReader, senderEndPoint);
}
}
public void Init(INatPunchListener listener)
{
_natPunchListener = listener;
}
private void Send<T>(T packet, IPEndPoint target) where T : class, new()
{
SocketError errorCode = 0;
_cacheWriter.Reset();
_cacheWriter.Put((byte)PacketProperty.NatMessage);
_netPacketProcessor.Write(_cacheWriter, packet);
_socket.SendTo(_cacheWriter.Data, 0, _cacheWriter.Length, target, ref errorCode);
}
public void NatIntroduce(
IPEndPoint hostInternal,
IPEndPoint hostExternal,
IPEndPoint clientInternal,
IPEndPoint clientExternal,
string additionalInfo)
{
var req = new NatIntroduceResponsePacket
{
Token = additionalInfo
};
//First packet (server) send to client
req.Internal = hostInternal;
req.External = hostExternal;
Send(req, clientExternal);
//Second packet (client) send to server
req.Internal = clientInternal;
req.External = clientExternal;
Send(req, hostExternal);
}
public void PollEvents()
{
if (_natPunchListener == null || (_successEvents.Count == 0 && _requestEvents.Count == 0))
return;
lock (_successEvents)
{
while (_successEvents.Count > 0)
{
var evt = _successEvents.Dequeue();
_natPunchListener.OnNatIntroductionSuccess(
evt.TargetEndPoint,
evt.Type,
evt.Token);
}
}
lock (_requestEvents)
{
while (_requestEvents.Count > 0)
{
var evt = _requestEvents.Dequeue();
_natPunchListener.OnNatIntroductionRequest(evt.LocalEndPoint, evt.RemoteEndPoint, evt.Token);
}
}
}
public void SendNatIntroduceRequest(string host, int port, string additionalInfo)
{
SendNatIntroduceRequest(NetUtils.MakeEndPoint(host, port), additionalInfo);
}
public void SendNatIntroduceRequest(IPEndPoint masterServerEndPoint, string additionalInfo)
{
//prepare outgoing data
string networkIp = NetUtils.GetLocalIp(LocalAddrType.IPv4);
if (string.IsNullOrEmpty(networkIp))
{
networkIp = NetUtils.GetLocalIp(LocalAddrType.IPv6);
}
Send(
new NatIntroduceRequestPacket
{
Internal = NetUtils.MakeEndPoint(networkIp, _socket.LocalPort),
Token = additionalInfo
},
masterServerEndPoint);
}
//We got request and must introduce
private void OnNatIntroductionRequest(NatIntroduceRequestPacket req, IPEndPoint senderEndPoint)
{
lock (_requestEvents)
{
_requestEvents.Enqueue(new RequestEventData
{
LocalEndPoint = req.Internal,
RemoteEndPoint = senderEndPoint,
Token = req.Token
});
}
}
//We got introduce and must punch
private void OnNatIntroductionResponse(NatIntroduceResponsePacket req)
{
NetDebug.Write(NetLogLevel.Trace, "[NAT] introduction received");
// send internal punch
var punchPacket = new NatPunchPacket {Token = req.Token};
Send(punchPacket, req.Internal);
NetDebug.Write(NetLogLevel.Trace, "[NAT] internal punch sent to " + req.Internal);
// hack for some routers
SocketError errorCode = 0;
_socket.Ttl = 2;
_socket.SendTo(new[] { (byte)PacketProperty.Empty }, 0, 1, req.External, ref errorCode);
// send external punch
_socket.Ttl = NetConstants.SocketTTL;
punchPacket.IsExternal = true;
Send(punchPacket, req.External);
NetDebug.Write(NetLogLevel.Trace, "[NAT] external punch sent to " + req.External);
}
//We got punch and can connect
private void OnNatPunch(NatPunchPacket req, IPEndPoint senderEndPoint)
{
//Read info
NetDebug.Write(NetLogLevel.Trace, "[NAT] punch received from {0} - additional info: {1}",
senderEndPoint, req.Token);
//Release punch success to client; enabling him to Connect() to Sender if token is ok
lock (_successEvents)
{
_successEvents.Enqueue(new SuccessEventData
{
TargetEndPoint = senderEndPoint,
Type = req.IsExternal ? NatAddressType.External : NatAddressType.Internal,
Token = req.Token
});
}
}
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/NatPunchModule.cs.meta
================================================
fileFormatVersion: 2
guid: be2d3965b2909b74a842c90154448111
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/NetConstants.cs
================================================
namespace LiteNetLib
{
/// <summary>
/// Sending method type
/// </summary>
public enum DeliveryMethod : byte
{
/// <summary>
/// Unreliable. Packets can be dropped, can be duplicated, can arrive without order.
/// </summary>
Unreliable = 4,
/// <summary>
/// Reliable. Packets won't be dropped, won't be duplicated, can arrive without order.
/// </summary>
ReliableUnordered = 0,
/// <summary>
/// Unreliable. Packets can be dropped, won't be duplicated, will arrive in order.
/// </summary>
Sequenced = 1,
/// <summary>
/// Reliable and ordered. Packets won't be dropped, won't be duplicated, will arrive in order.
/// </summary>
ReliableOrdered = 2,
/// <summary>
/// Reliable only last packet. Packets can be dropped (except the last one), won't be duplicated, will arrive in order.
/// </summary>
ReliableSequenced = 3
}
/// <summary>
/// Network constants. Can be tuned from sources for your purposes.
/// </summary>
public static class NetConstants
{
//can be tuned
public const int DefaultWindowSize = 64;
public const int SocketBufferSize = 1024 * 1024; //1mb
public const int SocketTTL = 255;
public const int HeaderSize = 1;
public const int ChanneledHeaderSize = 4;
public const int FragmentHeaderSize = 6;
public const int FragmentedHeaderTotalSize = ChanneledHeaderSize + FragmentHeaderSize;
public const ushort MaxSequence = 32768;
public const ushort HalfMaxSequence = MaxSequence / 2;
//protocol
internal const int ProtocolId = 11;
internal const int MaxUdpHeaderSize = 68;
internal static readonly int[] PossibleMtu =
{
576 - MaxUdpHeaderSize, //minimal
1232 - MaxUdpHeaderSize,
1460 - MaxUdpHeaderSize, //google cloud
1472 - MaxUdpHeaderSize, //VPN
1492 - MaxUdpHeaderSize, //Ethernet with LLC and SNAP, PPPoE (RFC 1042)
1500 - MaxUdpHeaderSize //Ethernet II (RFC 1191)
};
internal static readonly int MaxPacketSize = PossibleMtu[PossibleMtu.Length - 1];
//peer specific
public const byte MaxConnectionNumber = 4;
public const int PacketPoolSize = 1000;
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/NetConstants.cs.meta
================================================
fileFormatVersion: 2
guid: 53626ac03d7feb74b9b39561430c8c97
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/NetDebug.cs
================================================
using System;
using System.Diagnostics;
namespace LiteNetLib
{
public class InvalidPacketException : ArgumentException
{
public InvalidPacketException(string message) : base(message)
{
}
}
public class TooBigPacketException : InvalidPacketException
{
public TooBigPacketException(string message) : base(message)
{
}
}
public enum NetLogLevel
{
Warning,
Error,
Trace,
Info
}
/// <summary>
/// Interface to implement for your own logger
/// </summary>
public interface INetLogger
{
void WriteNet(NetLogLevel level, string str, params object[] args);
}
/// <summary>
/// Static class for defining your own LiteNetLib logger instead of Console.WriteLine
/// or Debug.Log if compiled with UNITY flag
/// </summary>
public static class NetDebug
{
public static INetLogger Logger = null;
private static readonly object DebugLogLock = new object();
private static void WriteLogic(NetLogLevel logLevel, string str, params object[] args)
{
lock (DebugLogLock)
{
if (Logger == null)
{
#if UNITY_4 || UNITY_5 || UNITY_5_3_OR_NEWER
UnityEngine.Debug.Log(string.Format(str, args));
#else
Console.WriteLine(str, args);
#endif
}
else
{
Logger.WriteNet(logLevel, str, args);
}
}
}
[Conditional("DEBUG_MESSAGES")]
internal static void Write(string str, params object[] args)
{
WriteLogic(NetLogLevel.Trace, str, args);
}
[Conditional("DEBUG_MESSAGES")]
internal static void Write(NetLogLevel level, string str, params object[] args)
{
WriteLogic(level, str, args);
}
[Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")]
internal static void WriteForce(string str, params object[] args)
{
WriteLogic(NetLogLevel.Trace, str, args);
}
[Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")]
internal static void WriteForce(NetLogLevel level, string str, params object[] args)
{
WriteLogic(level, str, args);
}
internal static void WriteError(string str, params object[] args)
{
WriteLogic(NetLogLevel.Error, str, args);
}
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/NetDebug.cs.meta
================================================
fileFormatVersion: 2
guid: 03c9260e78a794a4b8839e0054f491bd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/NetManager.cs
================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using LiteNetLib.Layers;
using LiteNetLib.Utils;
namespace LiteNetLib
{
public enum IPv6Mode
{
Disabled,
SeparateSocket,
DualMode
}
public sealed class NetPacketReader : NetDataReader
{
private NetPacket _packet;
private readonly NetManager _manager;
private readonly NetEvent _evt;
internal NetPacketReader(NetManager manager, NetEvent evt)
{
_manager = manager;
_evt = evt;
}
internal void SetSource(NetPacket packet, int headerSize)
{
if (packet == null)
return;
_packet = packet;
SetSource(packet.RawData, headerSize, packet.Size);
}
internal void RecycleInternal()
{
Clear();
if (_packet != null)
_manager.NetPacketPool.Recycle(_packet);
_packet = null;
_manager.RecycleEvent(_evt);
}
public void Recycle()
{
if(_manager.AutoRecycle)
throw new Exception("Recycle called with AutoRecycle enabled");
RecycleInternal();
}
}
internal sealed class NetEvent
{
public NetEvent Next;
public enum EType
{
Connect,
Disconnect,
Receive,
ReceiveUnconnected,
Error,
ConnectionLatencyUpdated,
Broadcast,
ConnectionRequest,
MessageDelivered
}
public EType Type;
public NetPeer Peer;
public IPEndPoint RemoteEndPoint;
public object UserData;
public int Latency;
public SocketError ErrorCode;
public DisconnectReason DisconnectReason;
public ConnectionRequest ConnectionRequest;
public DeliveryMethod DeliveryMethod;
public readonly NetPacketReader DataReader;
public NetEvent(NetManager manager)
{
DataReader = new NetPacketReader(manager, this);
}
}
/// <summary>
/// Main class for all network operations. Can be used as client and/or server.
/// </summary>
public class NetManager : INetSocketListener, IEnumerable<NetPeer>
{
private class IPEndPointComparer : IEqualityComparer<IPEndPoint>
{
public bool Equals(IPEndPoint x, IPEndPoint y)
{
return x.Address.Equals(y.Address) && x.Port == y.Port;
}
public int GetHashCode(IPEndPoint obj)
{
return obj.GetHashCode();
}
}
public struct NetPeerEnumerator : IEnumerator<NetPeer>
{
private readonly NetPeer _initialPeer;
private NetPeer _p;
public NetPeerEnumerator(NetPeer p)
{
_initialPeer = p;
_p = null;
}
public void Dispose()
{
}
public bool MoveNext()
{
_p = _p == null ? _initialPeer : _p.NextPeer;
return _p != null;
}
public void Reset()
{
throw new NotSupportedException();
}
public NetPeer Current
{
get { return _p; }
}
object IEnumerator.Current
{
get { return _p; }
}
}
#if DEBUG
private struct IncomingData
{
public byte[] Data;
public IPEndPoint EndPoint;
public DateTime TimeWhenGet;
}
private readonly List<IncomingData> _pingSimulationList = new List<IncomingData>();
private readonly Random _randomGenerator = new Random();
private const int MinLatencyThreshold = 5;
#endif
private readonly NetSocket _socket;
private Thread _logicThread;
private readonly AutoResetEvent _updateTriggerEvent = new AutoResetEvent(true);
private readonly Queue<NetEvent> _netEventsQueue;
private NetEvent _netEventPoolHead;
private readonly INetEventListener _netEventListener;
private readonly IDeliveryEventListener _deliveryEventListener;
private readonly Dictionary<IPEndPoint, NetPeer> _peersDict;
private readonly Dictionary<IPEndPoint, ConnectionRequest> _requestsDict;
private readonly ReaderWriterLockSlim _peersLock;
private volatile NetPeer _headPeer;
private volatile int _connectedPeersCount;
private readonly List<NetPeer> _connectedPeerListCache;
private NetPeer[] _peersArray;
private readonly PacketLayerBase _extraPacketLayer;
private int _lastPeerId;
private readonly Queue<int> _peerIds;
private byte _channelsCount = 1;
internal readonly NetPacketPool NetPacketPool;
//config section
/// <summary>
/// Enable messages receiving without connection. (with SendUnconnectedMessage method)
/// </summary>
public bool UnconnectedMessagesEnabled = false;
/// <summary>
/// Enable nat punch messages
/// </summary>
public bool NatPunchEnabled = false;
/// <summary>
/// Library logic update and send period in milliseconds
/// </summary>
public int UpdateTime = 15;
/// <summary>
/// Interval for latency detection and checking connection
/// </summary>
public int PingInterval = 1000;
/// <summary>
/// If NetManager doesn't receive any packet from remote peer during this time then connection will be closed
/// (including library internal keepalive packets)
/// </summary>
public int DisconnectTimeout = 5000;
/// <summary>
/// Simulate packet loss by dropping random amount of packets. (Works only in DEBUG mode)
/// </summary>
public bool SimulatePacketLoss = false;
/// <summary>
/// Simulate latency by holding packets for random time. (Works only in DEBUG mode)
/// </summary>
public bool SimulateLatency = false;
/// <summary>
/// Chance of packet loss when simulation enabled. value in percents (1 - 100).
/// </summary>
public int SimulationPacketLossChance = 10;
/// <summary>
/// Minimum simulated latency
/// </summary>
public int SimulationMinLatency = 30;
/// <summary>
/// Maximum simulated latency
/// </summary>
public int SimulationMaxLatency = 100;
/// <summary>
/// Events automatically will be called without PollEvents method from another thread
/// </summary>
public bool UnsyncedEvents = false;
/// <summary>
/// If true - receive event will be called from "receive" thread immediately otherwise on PollEvents call
/// </summary>
public bool UnsyncedReceiveEvent = false;
/// <summary>
/// If true - delivery event will be called from "receive" thread immediately otherwise on PollEvents call
/// </summary>
public bool UnsyncedDeliveryEvent = false;
/// <summary>
/// Allows receive broadcast packets
/// </summary>
public bool BroadcastReceiveEnabled = false;
/// <summary>
/// Delay between initial connection attempts
/// </summary>
public int ReconnectDelay = 500;
/// <summary>
/// Maximum connection attempts before client stops and call disconnect event.
/// </summary>
public int MaxConnectAttempts = 10;
/// <summary>
/// Enables socket option "ReuseAddress" for specific purposes
/// </summary>
public bool ReuseAddress = false;
/// <summary>
/// Statistics of all connections
/// </summary>
public readonly NetStatistics Statistics;
/// <summary>
/// Toggles the collection of network statistics for the instance and all known peers
/// </summary>
public bool EnableStatistics = false;
/// <summary>
/// NatPunchModule for NAT hole punching operations
/// </summary>
public readonly NatPunchModule NatPunchModule;
/// <summary>
/// Returns true if socket listening and update thread is running
/// </summary>
public bool IsRunning { get { return _socket.IsRunning; } }
/// <summary>
/// Local EndPoint (host and port)
/// </summary>
public int LocalPort { get { return _socket.LocalPort; } }
/// <summary>
/// Automatically recycle NetPacketReader after OnReceive event
/// </summary>
public bool AutoRecycle;
/// <summary>
/// IPv6 support
/// </summary>
public IPv6Mode IPv6Enabled = IPv6Mode.SeparateSocket;
/// <summary>
/// First peer. Useful for Client mode
/// </summary>
public NetPeer FirstPeer
{
get { return _headPeer; }
}
/// <summary>
/// QoS channel count per message type (value must be between 1 and 64 channels)
/// </summary>
public byte ChannelsCount
{
get { return _channelsCount; }
set
{
if (value < 1 || value > 64)
throw new ArgumentException("Channels count must be between 1 and 64");
_channelsCount = value;
}
}
/// <summary>
/// Returns connected peers list (with internal cached list)
/// </summary>
public List<NetPeer> ConnectedPeerList
{
get
{
GetPeersNonAlloc(_connectedPeerListCache, ConnectionState.Connected);
return _connectedPeerListCache;
}
}
/// <summary>
/// Gets peer by peer id
/// </summary>
/// <param name="id">id of peer</param>
/// <returns>Peer if peer with id exist, otherwise null</returns>
public NetPeer GetPeerById(int id)
{
return _peersArray[id];
}
/// <summary>
/// Returns connected peers count
/// </summary>
public int ConnectedPeersCount { get { return _connectedPeersCount; } }
public int ExtraPacketSizeForLayer
{
get { return _extraPacketLayer != null ? _extraPacketLayer.ExtraPacketSizeForLayer : 0; }
}
private bool TryGetPeer(IPEndPoint endPoint, out NetPeer peer)
{
_peersLock.EnterReadLock();
bool result = _peersDict.TryGetValue(endPoint, out peer);
_peersLock.ExitReadLock();
return result;
}
private void AddPeer(NetPeer peer)
{
_peersLock.EnterWriteLock();
if (_headPeer != null)
{
peer.NextPeer = _headPeer;
_headPeer.PrevPeer = peer;
}
_headPeer = peer;
_peersDict.Add(peer.EndPoint, peer);
if (peer.Id >= _peersArray.Length)
{
int newSize = _peersArray.Length * 2;
while (peer.Id >= newSize)
newSize *= 2;
Array.Resize(ref _peersArray, newSize);
}
_peersArray[peer.Id] = peer;
_peersLock.ExitWriteLock();
}
private void RemovePeer(NetPeer peer)
{
_peersLock.EnterWriteLock();
RemovePeerInternal(peer);
_peersLock.ExitWriteLock();
}
private void RemovePeerInternal(NetPeer peer)
{
if (!_peersDict.Remove(peer.EndPoint))
return;
if (peer == _headPeer)
_headPeer = peer.NextPeer;
if (peer.PrevPeer != null)
peer.PrevPeer.NextPeer = peer.NextPeer;
if (peer.NextPeer != null)
peer.NextPeer.PrevPeer = peer.PrevPeer;
peer.PrevPeer = null;
_peersArray[peer.Id] = null;
lock (_peerIds)
_peerIds.Enqueue(peer.Id);
}
/// <summary>
/// NetManager constructor
/// </summary>
/// <param name="listener">Network events listener (also can implement IDeliveryEventListener)</param>
/// <param name="extraPacketLayer">Extra processing of packages, like CRC checksum or encryption. All connected NetManagers must have same layer.</param>
public NetManager(INetEventListener listener, PacketLayerBase extraPacketLayer = null)
{
_socket = new NetSocket(this);
_netEventListener = listener;
_deliveryEventListener = listener as IDeliveryEventListener;
_netEventsQueue = new Queue<NetEvent>();
NetPacketPool = new NetPacketPool();
NatPunchModule = new NatPunchModule(_socket);
Statistics = new NetStatistics();
_connectedPeerListCache = new List<NetPeer>();
_peersDict = new Dictionary<IPEndPoint, NetPeer>(new IPEndPointComparer());
_requestsDict = new Dictionary<IPEndPoint, ConnectionRequest>(new IPEndPointComparer());
_peersLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
_peerIds = new Queue<int>();
_peersArray = new NetPeer[32];
_extraPacketLayer = extraPacketLayer;
}
internal void ConnectionLatencyUpdated(NetPeer fromPeer, int latency)
{
CreateEvent(NetEvent.EType.ConnectionLatencyUpdated, fromPeer, latency: latency);
}
internal void MessageDelivered(NetPeer fromPeer, object userData)
{
if(_deliveryEventListener != null)
CreateEvent(NetEvent.EType.MessageDelivered, fromPeer, userData: userData);
}
internal int SendRawAndRecycle(NetPacket packet, IPEndPoint remoteEndPoint)
{
var result = SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint);
NetPacketPool.Recycle(packet);
return result;
}
internal int SendRaw(NetPacket packet, IPEndPoint remoteEndPoint)
{
return SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint);
}
internal int SendRaw(byte[] message, int start, int length, IPEndPoint remoteEndPoint)
{
if (!_socket.IsRunning)
return 0;
SocketError errorCode = 0;
int result;
if (_extraPacketLayer != null)
{
var expandedPacket = NetPacketPool.GetPacket(length + _extraPacketLayer.ExtraPacketSizeForLayer);
Buffer.BlockCopy(message, start, expandedPacket.RawData, 0, length);
int newStart = 0;
_extraPacketLayer.ProcessOutBoundPacket(remoteEndPoint, ref expandedPacket.RawData, ref newStart, ref length);
result = _socket.SendTo(expandedPacket.RawData, newStart, length, remoteEndPoint, ref errorCode);
NetPacketPool.Recycle(expandedPacket);
}
else
{
result = _socket.SendTo(message, start, length, remoteEndPoint, ref errorCode);
}
NetPeer fromPeer;
switch (errorCode)
{
case SocketError.MessageSize:
NetDebug.Write(NetLogLevel.Trace, "[SRD] 10040, datalen: {0}", length);
return -1;
case SocketError.HostUnreachable:
if (TryGetPeer(remoteEndPoint, out fromPeer))
DisconnectPeerForce(fromPeer, DisconnectReason.HostUnreachable, errorCode, null);
CreateEvent(NetEvent.EType.Error, remoteEndPoint: remoteEndPoint, errorCode: errorCode);
return -1;
case SocketError.NetworkUnreachable:
if (TryGetPeer(remoteEndPoint, out fromPeer))
DisconnectPeerForce(fromPeer, DisconnectReason.NetworkUnreachable, errorCode, null);
CreateEvent(NetEvent.EType.Error, remoteEndPoint: remoteEndPoint, errorCode: errorCode);
return -1;
}
if (result <= 0)
return 0;
if (EnableStatistics)
{
Statistics.IncrementPacketsSent();
Statistics.AddBytesSent(length);
}
return result;
}
internal void DisconnectPeerForce(NetPeer peer,
DisconnectReason reason,
SocketError socketErrorCode,
NetPacket eventData)
{
DisconnectPeer(peer, reason, socketErrorCode, true, null, 0, 0, eventData);
}
private void DisconnectPeer(
NetPeer peer,
DisconnectReason reason,
SocketError socketErrorCode,
bool force,
byte[] data,
int start,
int count,
NetPacket eventData)
{
var shutdownResult = peer.Shutdown(data, start, count, force);
if (shutdownResult == ShutdownResult.None)
return;
if(shutdownResult == ShutdownResult.WasConnected)
Interlocked.Decrement(ref _connectedPeersCount);
Thread.MemoryBarrier();
CreateEvent(
NetEvent.EType.Disconnect,
peer,
errorCode: socketErrorCode,
disconnectReason: reason,
readerSource: eventData);
}
private void CreateEvent(
NetEvent.EType type,
NetPeer peer = null,
IPEndPoint remoteEndPoint = null,
SocketError errorCode = 0,
int latency = 0,
DisconnectReason disconnectReason = DisconnectReason.ConnectionFailed,
ConnectionRequest connectionRequest = null,
DeliveryMethod deliveryMethod = DeliveryMethod.Unreliable,
NetPacket readerSource = null,
object userData = null)
{
NetEvent evt;
bool unsyncEvent = UnsyncedEvents;
if (type == NetEvent.EType.Connect)
Interlocked.Increment(ref _connectedPeersCount);
else if (type == NetEvent.EType.MessageDelivered)
unsyncEvent = UnsyncedDeliveryEvent;
do
{
evt = _netEventPoolHead;
if (evt == null)
{
evt = new NetEvent(this);
break;
}
} while (evt != Interlocked.CompareExchange(ref _netEventPoolHead, evt.Next, evt));
evt.Type = type;
evt.DataReader.SetSource(readerSource, readerSource == null ? 0 : readerSource.GetHeaderSize());
evt.Peer = peer;
evt.RemoteEndPoint = remoteEndPoint;
evt.Latency = latency;
evt.ErrorCode = errorCode;
evt.DisconnectReason = disconnectReason;
evt.ConnectionRequest = connectionRequest;
evt.DeliveryMethod = deliveryMethod;
evt.UserData = userData;
if (unsyncEvent)
{
ProcessEvent(evt);
}
else
{
lock (_netEventsQueue)
_netEventsQueue.Enqueue(evt);
}
}
private void ProcessEvent(NetEvent evt)
{
NetDebug.Write("[NM] Processing event: " + evt.Type);
bool emptyData = evt.DataReader.IsNull;
switch (evt.Type)
{
case NetEvent.EType.Connect:
_netEventListener.OnPeerConnected(evt.Peer);
break;
case NetEvent.EType.Disconnect:
var info = new DisconnectInfo
{
Reason = evt.DisconnectReason,
AdditionalData = evt.DataReader,
SocketErrorCode = evt.ErrorCode
};
_netEventListener.OnPeerDisconnected(evt.Peer, info);
break;
case NetEvent.EType.Receive:
_netEventListener.OnNetworkReceive(evt.Peer, evt.DataReader, evt.DeliveryMethod);
break;
case NetEvent.EType.ReceiveUnconnected:
_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.BasicMessage);
break;
case NetEvent.EType.Broadcast:
_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.Broadcast);
break;
case NetEvent.EType.Error:
_netEventListener.OnNetworkError(evt.RemoteEndPoint, evt.ErrorCode);
break;
case NetEvent.EType.ConnectionLatencyUpdated:
_netEventListener.OnNetworkLatencyUpdate(evt.Peer, evt.Latency);
break;
case NetEvent.EType.ConnectionRequest:
_netEventListener.OnConnectionRequest(evt.ConnectionRequest);
break;
case NetEvent.EType.MessageDelivered:
_deliveryEventListener.OnMessageDelivered(evt.Peer, evt.UserData);
break;
}
//Recycle if not message
if (emptyData)
RecycleEvent(evt);
else if (AutoRecycle)
evt.DataReader.RecycleInternal();
}
internal void RecycleEvent(NetEvent evt)
{
evt.Peer = null;
evt.ErrorCode = 0;
evt.RemoteEndPoint = null;
evt.ConnectionRequest = null;
do
{
evt.Next = _netEventPoolHead;
} while (evt.Next != Interlocked.CompareExchange(ref _netEventPoolHead, evt, evt.Next));
}
//Update function
private void UpdateLogic()
{
var peersToRemove = new List<NetPeer>();
var stopwatch = new Stopwatch();
stopwatch.Start();
while (_socket.IsRunning)
{
#if DEBUG
if (SimulateLatency)
{
var time = DateTime.UtcNow;
lock (_pingSimulationList)
{
for (int i = 0; i < _pingSimulationList.Count; i++)
{
var incomingData = _pingSimulationList[i];
if (incomingData.TimeWhenGet <= time)
{
DataReceived(incomingData.Data, incomingData.Data.Length, incomingData.EndPoint);
_pingSimulationList.RemoveAt(i);
i--;
}
}
}
}
#endif
int elapsed = (int)stopwatch.ElapsedMilliseconds;
elapsed = elapsed <= 0 ? 1 : elapsed;
stopwatch.Reset();
stopwatch.Start();
for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
{
if (netPeer.ConnectionState == ConnectionState.Disconnected && netPeer.TimeSinceLastPacket > DisconnectTimeout)
{
peersToRemove.Add(netPeer);
}
else
{
netPeer.Update(elapsed);
}
}
if (peersToRemove.Count > 0)
{
_peersLock.EnterWriteLock();
for (int i = 0; i < peersToRemove.Count; i++)
RemovePeerInternal(peersToRemove[i]);
_peersLock.ExitWriteLock();
peersToRemove.Clear();
}
int sleepTime = UpdateTime - (int)stopwatch.ElapsedMilliseconds;
if (sleepTime > 0)
_updateTriggerEvent.WaitOne(sleepTime);
}
stopwatch.Stop();
}
void INetSocketListener.OnMessageReceived(byte[] data, int length, SocketError errorCode, IPEndPoint remoteEndPoint)
{
if (errorCode != 0)
{
CreateEvent(NetEvent.EType.Error, errorCode: errorCode);
NetDebug.WriteError("[NM] Receive error: {0}", errorCode);
return;
}
#if DEBUG
if (SimulatePacketLoss && _randomGenerator.NextDouble() * 100 < SimulationPacketLossChance)
{
//drop packet
return;
}
if (SimulateLatency)
{
int latency = _randomGenerator.Next(SimulationMinLatency, SimulationMaxLatency);
if (latency > MinLatencyThreshold)
{
byte[] holdedData = new byte[length];
Buffer.BlockCopy(data, 0, holdedData, 0, length);
lock (_pingSimulationList)
{
_pingSimulationList.Add(new IncomingData
{
Data = holdedData,
EndPoint = remoteEndPoint,
TimeWhenGet = DateTime.UtcNow.AddMilliseconds(latency)
});
}
//hold packet
return;
}
}
#endif
try
{
//ProcessEvents
DataReceived(data, length, remoteEndPoint);
}
catch(Exception e)
{
//protects socket receive thread
NetDebug.WriteError("[NM] SocketReceiveThread error: " + e );
}
}
internal NetPeer OnConnectionSolved(ConnectionRequest request, byte[] rejectData, int start, int length)
{
NetPeer netPeer = null;
if (request.Result == ConnectionRequestResult.RejectForce)
{
NetDebug.Write(NetLogLevel.Trace, "[NM] Peer connect reject force.");
if (rejectData != null && length > 0)
{
var shutdownPacket = NetPacketPool.GetWithProperty(PacketProperty.Disconnect, length);
shutdownPacket.ConnectionNumber = request.ConnectionNumber;
FastBitConverter.GetBytes(shutdownPacket.RawData, 1, request.ConnectionTime);
if (shutdownPacket.Size >= NetConstants.PossibleMtu[0])
NetDebug.WriteError("[Peer] Disconnect additional data size more than MTU!");
else
Buffer.BlockCopy(rejectData, start, shutdownPacket.RawData, 9, length);
SendRawAndRecycle(shutdownPacket, request.RemoteEndPoint);
}
}
else
{
_peersLock.EnterUpgradeableReadLock();
if (_peersDict.TryGetValue(request.RemoteEndPoint, out netPeer))
{
//already have peer
_peersLock.ExitUpgradeableReadLock();
}
else if (request.Result == ConnectionRequestResult.Reject)
{
netPeer = new NetPeer(this, request.RemoteEndPoint, GetNextPeerId());
netPeer.Reject(request.ConnectionTime, request.ConnectionNumber, rejectData, start, length);
AddPeer(netPeer);
_peersLock.ExitUpgradeableReadLock();
NetDebug.Write(NetLogLevel.Trace, "[NM] Peer connect reject.");
}
else //Accept
{
netPeer = new NetPeer(this, request.RemoteEndPoint, GetNextPeerId(), request.ConnectionTime, request.ConnectionNumber);
AddPeer(netPeer);
_peersLock.ExitUpgradeableReadLock();
CreateEvent(NetEvent.EType.Connect, netPeer);
NetDebug.Write(NetLogLevel.Trace, "[NM] Received peer connection Id: {0}, EP: {1}",
netPeer.ConnectTime, netPeer.EndPoint);
}
}
lock(_requestsDict)
_requestsDict.Remove(request.RemoteEndPoint);
return netPeer;
}
private int GetNextPeerId()
{
lock (_peerIds)
return _peerIds.Count == 0 ? _lastPeerId++ : _peerIds.Dequeue();
}
private void ProcessConnectRequest(
IPEndPoint remoteEndPoint,
NetPeer netPeer,
NetConnectRequestPacket connRequest)
{
byte connectionNumber = connRequest.ConnectionNumber;
ConnectionRequest req;
//if we have peer
if (netPeer != null)
{
var processResult = netPeer.ProcessConnectRequest(connRequest);
NetDebug.Write("ConnectRequest LastId: {0}, NewId: {1}, EP: {2}, Result: {3}",
netPeer.ConnectTime,
connRequest.ConnectionTime,
remoteEndPoint,
processResult);
switch (processResult)
{
case ConnectRequestResult.Reconnection:
DisconnectPeerForce(netPeer, DisconnectReason.Reconnect, 0, null);
RemovePeer(netPeer);
//go to new connection
break;
case ConnectRequestResult.NewConnection:
RemovePeer(netPeer);
//go to new connection
break;
case ConnectRequestResult.P2PLose:
DisconnectPeerForce(netPeer, DisconnectReason.PeerToPeerConnection, 0, null);
RemovePeer(netPeer);
//go to new connection
break;
default:
//no operations needed
return;
}
//ConnectRequestResult.NewConnection
//Set next connection number
if(processResult != ConnectRequestResult.P2PLose)
connectionNumber = (byte)((netPeer.ConnectionNum + 1) % NetConstants.MaxConnectionNumber);
//To reconnect peer
}
else
{
NetDebug.Write("ConnectRequest Id: {0}, EP: {1}", connRequest.ConnectionTime, remoteEndPoint);
}
lock (_requestsDict)
{
if (_requestsDict.TryGetValue(remoteEndPoint, out req))
{
req.UpdateRequest(connRequest);
return;
}
req = new ConnectionRequest(
connRequest.ConnectionTime,
connectionNumber,
connRequest.Data,
remoteEndPoint,
this);
_requestsDict.Add(remoteEndPoint, req);
}
NetDebug.Write("[NM] Creating request event: " + connRequest.ConnectionTime);
CreateEvent(NetEvent.EType.ConnectionRequest, connectionRequest: req);
}
private void DataReceived(byte[] reusableBuffer, int count, IPEndPoint remoteEndPoint)
{
if (EnableStatistics)
{
Statistics.IncrementPacketsReceived();
Statistics.AddBytesReceived(count);
}
int start = 0;
if (_extraPacketLayer != null)
{
_extraPacketLayer.ProcessInboundPacket(remoteEndPoint, ref reusableBuffer, ref start, ref count);
if (count == 0)
return;
}
//empty packet
if (reusableBuffer[start] == (byte) PacketProperty.Empty)
return;
//Try read packet
NetPacket packet = NetPacketPool.GetPacket(count);
if (!packet.FromBytes(reusableBuffer, start, count))
{
NetPacketPool.Recycle(packet);
NetDebug.WriteError("[NM] DataReceived: bad!");
return;
}
switch (packet.Property)
{
//special case connect request
case PacketProperty.ConnectRequest:
if (NetConnectRequestPacket.GetProtocolId(packet) != NetConstants.ProtocolId)
{
SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.InvalidProtocol), remoteEndPoint);
return;
}
break;
//unconnected messages
case PacketProperty.Broadcast:
if (!BroadcastReceiveEnabled)
return;
CreateEvent(NetEvent.EType.Broadcast, remoteEndPoint: remoteEndPoint, readerSource: packet);
return;
case PacketProperty.UnconnectedMessage:
if (!UnconnectedMessagesEnabled)
return;
CreateEvent(NetEvent.EType.ReceiveUnconnected, remoteEndPoint: remoteEndPoint, readerSource: packet);
return;
case PacketProperty.NatMessage:
if (NatPunchEnabled)
NatPunchModule.ProcessMessage(remoteEndPoint, packet);
return;
}
//Check normal packets
NetPeer netPeer;
_peersLock.EnterReadLock();
bool peerFound = _peersDict.TryGetValue(remoteEndPoint, out netPeer);
_peersLock.ExitReadLock();
switch (packet.Property)
{
case PacketProperty.ConnectRequest:
var connRequest = NetConnectRequestPacket.FromData(packet);
if (connRequest != null)
ProcessConnectRequest(remoteEndPoint, netPeer, connRequest);
break;
case PacketProperty.PeerNotFound:
if (peerFound)
{
if (netPeer.ConnectionState != ConnectionState.Connected)
return;
if (packet.Size == 1)
{
//first reply
var p = NetPacketPool.GetWithProperty(PacketProperty.PeerNotFound, 9);
p.RawData[1] = 0;
FastBitConverter.GetBytes(p.RawData, 2, netPeer.ConnectTime);
SendRawAndRecycle(p, remoteEndPoint);
NetDebug.Write("PeerNotFound sending connectTime: {0}", netPeer.ConnectTime);
}
else if (packet.Size == 10 && packet.RawData[1] == 1 && BitConverter.ToInt64(packet.RawData, 2) == netPeer.ConnectTime)
{
//second reply
NetDebug.Write("PeerNotFound received our connectTime: {0}", netPeer.ConnectTime);
DisconnectPeerForce(netPeer, DisconnectReason.RemoteConnectionClose, 0, null);
}
}
else if (packet.Size == 10 && packet.RawData[1] == 0)
{
//send reply back
packet.RawData[1] = 1;
SendRawAndRecycle(packet, remoteEndPoint);
}
break;
case PacketProperty.InvalidProtocol:
if (peerFound && netPeer.ConnectionState == ConnectionState.Outgoing)
DisconnectPeerForce(netPeer, DisconnectReason.InvalidProtocol, 0, null);
break;
case PacketProperty.Disconnect:
if (peerFound)
{
var disconnectResult = netPeer.ProcessDisconnect(packet);
if (disconnectResult == DisconnectResult.None)
{
NetPacketPool.Recycle(packet);
return;
}
DisconnectPeerForce(
netPeer,
disconnectResult == DisconnectResult.Disconnect
? DisconnectReason.RemoteConnectionClose
: DisconnectReason.ConnectionRejected,
0, packet);
}
else
{
NetPacketPool.Recycle(packet);
}
//Send shutdown
SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.ShutdownOk), remoteEndPoint);
break;
case PacketProperty.ConnectAccept:
if (!peerFound)
return;
var connAccept = NetConnectAcceptPacket.FromData(packet);
if (connAccept != null && netPeer.ProcessConnectAccept(connAccept))
CreateEvent(NetEvent.EType.Connect, netPeer);
break;
default:
if(peerFound)
netPeer.ProcessPacket(packet);
else
SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.PeerNotFound), remoteEndPoint);
break;
}
}
internal void CreateReceiveEvent(NetPacket packet, DeliveryMethod method, int headerSize, NetPeer fromPeer)
{
NetEvent evt;
do
{
evt = _netEventPoolHead;
if (evt == null)
{
evt = new NetEvent(this);
break;
}
} while (evt != Interlocked.CompareExchange(ref _netEventPoolHead, evt.Next, evt));
evt.Type = NetEvent.EType.Receive;
evt.DataReader.SetSource(packet, headerSize);
evt.Peer = fromPeer;
evt.DeliveryMethod = method;
if (UnsyncedEvents || UnsyncedReceiveEvent)
{
ProcessEvent(evt);
}
else
{
lock (_netEventsQueue)
_netEventsQueue.Enqueue(evt);
}
}
/// <summary>
/// Send data to all connected peers (channel - 0)
/// </summary>
/// <param name="writer">DataWriter with data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
public void SendToAll(NetDataWriter writer, DeliveryMethod options)
{
SendToAll(writer.Data, 0, writer.Length, options);
}
/// <summary>
/// Send data to all connected peers (channel - 0)
/// </summary>
/// <param name="data">Data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
public void SendToAll(byte[] data, DeliveryMethod options)
{
SendToAll(data, 0, data.Length, options);
}
/// <summary>
/// Send data to all connected peers (channel - 0)
/// </summary>
/// <param name="data">Data</param>
/// <param name="start">Start of data</param>
/// <param name="length">Length of data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
public void SendToAll(byte[] data, int start, int length, DeliveryMethod options)
{
SendToAll(data, start, length, 0, options);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="writer">DataWriter with data</param>
/// <param name="channelNumber">Number of channel (from 0 to channelsCount - 1)</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options)
{
SendToAll(writer.Data, 0, writer.Length, channelNumber, options);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="data">Data</param>
/// <param name="channelNumber">Number of channel (from 0 to channelsCount - 1)</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options)
{
SendToAll(data, 0, data.Length, channelNumber, options);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="data">Data</param>
/// <param name="start">Start of data</param>
/// <param name="length">Length of data</param>
/// <param name="channelNumber">Number of channel (from 0 to channelsCount - 1)</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options)
{
try
{
_peersLock.EnterReadLock();
for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
netPeer.Send(data, start, length, channelNumber, options);
}
finally
{
_peersLock.ExitReadLock();
}
}
/// <summary>
/// Send data to all connected peers (channel - 0)
/// </summary>
/// <param name="writer">DataWriter with data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <param name="excludePeer">Excluded peer</param>
public void SendToAll(NetDataWriter writer, DeliveryMethod options, NetPeer excludePeer)
{
SendToAll(writer.Data, 0, writer.Length, 0, options, excludePeer);
}
/// <summary>
/// Send data to all connected peers (channel - 0)
/// </summary>
/// <param name="data">Data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <param name="excludePeer">Excluded peer</param>
public void SendToAll(byte[] data, DeliveryMethod options, NetPeer excludePeer)
{
SendToAll(data, 0, data.Length, 0, options, excludePeer);
}
/// <summary>
/// Send data to all connected peers (channel - 0)
/// </summary>
/// <param name="data">Data</param>
/// <param name="start">Start of data</param>
/// <param name="length">Length of data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <param name="excludePeer">Excluded peer</param>
public void SendToAll(byte[] data, int start, int length, DeliveryMethod options, NetPeer excludePeer)
{
SendToAll(data, start, length, 0, options, excludePeer);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="writer">DataWriter with data</param>
/// <param name="channelNumber">Number of channel (from 0 to channelsCount - 1)</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <param name="excludePeer">Excluded peer</param>
public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options, NetPeer excludePeer)
{
SendToAll(writer.Data, 0, writer.Length, channelNumber, options, excludePeer);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="data">Data</param>
/// <param name="channelNumber">Number of channel (from 0 to channelsCount - 1)</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <param name="excludePeer">Excluded peer</param>
public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options, NetPeer excludePeer)
{
SendToAll(data, 0, data.Length, channelNumber, options, excludePeer);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="data">Data</param>
/// <param name="start">Start of data</param>
/// <param name="length">Length of data</param>
/// <param name="channelNumber">Number of channel (from 0 to channelsCount - 1)</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <param name="excludePeer">Excluded peer</param>
public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options, NetPeer excludePeer)
{
try
{
_peersLock.EnterReadLock();
for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
{
if (netPeer != excludePeer)
netPeer.Send(data, start, length, channelNumber, options);
}
}
finally
{
_peersLock.ExitReadLock();
}
}
/// <summary>
/// Start logic thread and listening on available port
/// </summary>
public bool Start()
{
return Start(0);
}
/// <summary>
/// Start logic thread and listening on selected port
/// </summary>
/// <param name="addressIPv4">bind to specific ipv4 address</param>
/// <param name="addressIPv6">bind to specific ipv6 address</param>
/// <param name="port">port to listen</param>
public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port)
{
if (!_socket.Bind(addressIPv4, addressIPv6, port, ReuseAddress, IPv6Enabled))
return false;
_logicThread = new Thread(UpdateLogic) { Name = "LogicThread", IsBackground = true };
_logicThread.Start();
return true;
}
/// <summary>
/// Start logic thread and listening on selected port
/// </summary>
/// <param name="addressIPv4">bind to specific ipv4 address</param>
/// <param name="addressIPv6">bind to specific ipv6 address</param>
/// <param name="port">port to listen</param>
public bool Start(string addressIPv4, string addressIPv6, int port)
{
IPAddress ipv4 = NetUtils.ResolveAddress(addressIPv4);
IPAddress ipv6 = NetUtils.ResolveAddress(addressIPv6);
return Start(ipv4, ipv6, port);
}
/// <summary>
/// Start logic thread and listening on selected port
/// </summary>
/// <param name="port">port to listen</param>
public bool Start(int port)
{
return Start(IPAddress.Any, IPAddress.IPv6Any, port);
}
/// <summary>
/// Send message without connection
/// </summary>
/// <param name="message">Raw data</param>
/// <param name="remoteEndPoint">Packet destination</param>
/// <returns>Operation result</returns>
public bool SendUnconnectedMessage(byte[] message, IPEndPoint remoteEndPoint)
{
return SendUnconnectedMessage(message, 0, message.Length, remoteEndPoint);
}
/// <summary>
/// Send message without connection
/// </summary>
/// <param name="writer">Data serializer</param>
/// <param name="remoteEndPoint">Packet destination</param>
/// <returns>Operation result</returns>
public bool SendUnconnectedMessage(NetDataWriter writer, IPEndPoint remoteEndPoint)
{
return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint);
}
/// <summary>
/// Send message without connection
/// </summary>
/// <param name="message">Raw data</param>
/// <param name="start">data start</param>
/// <param name="length">data length</param>
/// <param name="remoteEndPoint">Packet destination</param>
/// <returns>Operation result</returns>
public bool SendUnconnectedMessage(byte[] message, int start, int length, IPEndPoint remoteEndPoint)
{
//No need for CRC here, SendRaw does that
NetPacket packet = NetPacketPool.GetWithData(PacketProperty.UnconnectedMessage, message, start, length);
return SendRawAndRecycle(packet, remoteEndPoint) > 0;
}
public bool SendBroadcast(NetDataWriter writer, int port)
{
return SendBroadcast(writer.Data, 0, writer.Length, port);
}
public bool SendBroadcast(byte[] data, int port)
{
return SendBroadcast(data, 0, data.Length, port);
}
public bool SendBroadcast(byte[] data, int start, int length, int port)
{
NetPacket packet;
if (_extraPacketLayer != null)
{
var headerSize = NetPacket.GetHeaderSize(PacketProperty.Broadcast);
packet = NetPacketPool.GetPacket(headerSize + length + _extraPacketLayer.ExtraPacketSizeForLayer);
packet.Property = PacketProperty.Broadcast;
Buffer.BlockCopy(data, start, packet.RawData, headerSize, length);
var checksumComputeStart = 0;
int preCrcLength = length + headerSize;
_extraPacketLayer.ProcessOutBoundPacket(null, ref packet.RawData, ref checksumComputeStart, ref preCrcLength);
}
else
{
packet = NetPacketPool.GetWithData(PacketProperty.Broadcast, data, start, length);
}
bool result = _socket.SendBroadcast(packet.RawData, 0, packet.Size, port);
NetPacketPool.Recycle(packet);
return result;
}
/// <summary>
/// Triggers update and send logic immediately (works asynchronously)
/// </summary>
public void TriggerUpdate()
{
_updateTriggerEvent.Set();
}
/// <summary>
/// Receive all pending events. Call this in game update code
/// </summary>
public void PollEvents()
{
if (UnsyncedEvents)
return;
int eventsCount;
lock (_netEventsQueue)
eventsCount = _netEventsQueue.Count;
for(int i = 0; i < eventsCount; i++)
{
NetEvent evt;
lock (_netEventsQueue)
evt = _netEventsQueue.Dequeue();
ProcessEvent(evt);
}
}
/// <summary>
/// Connect to remote host
/// </summary>
/// <param name="address">Server IP or hostname</param>
/// <param name="port">Server Port</param>
/// <param name="key">Connection key</param>
/// <returns>New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting</returns>
/// <exception cref="InvalidOperationException">Manager is not running. Call <see cref="Start()"/></exception>
public NetPeer Connect(string address, int port, string key)
{
return Connect(address, port, NetDataWriter.FromString(key));
}
/// <summary>
/// Connect to remote host
/// </summary>
/// <param name="address">Server IP or hostname</param>
/// <param name="port">Server Port</param>
/// <param name="connectionData">Additional data for remote peer</param>
/// <returns>New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting</returns>
/// <exception cref="InvalidOperationException">Manager is not running. Call <see cref="Start()"/></exception>
public NetPeer Connect(string address, int port, NetDataWriter connectionData)
{
IPEndPoint ep;
try
{
ep = NetUtils.MakeEndPoint(address, port);
}
catch
{
CreateEvent(NetEvent.EType.Disconnect, disconnectReason: DisconnectReason.UnknownHost);
return null;
}
return Connect(ep, connectionData);
}
/// <summary>
/// Connect to remote host
/// </summary>
/// <param name="target">Server end point (ip and port)</param>
/// <param name="key">Connection key</param>
/// <returns>New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting</returns>
/// <exception cref="InvalidOperationException">Manager is not running. Call <see cref="Start()"/></exception>
public NetPeer Connect(IPEndPoint target, string key)
{
return Connect(target, NetDataWriter.FromString(key));
}
/// <summary>
/// Connect to remote host
/// </summary>
/// <param name="target">Server end point (ip and port)</param>
/// <param name="connectionData">Additional data for remote peer</param>
/// <returns>New NetPeer if new connection, Old NetPeer if already connected, null peer if there is ConnectionRequest awaiting</returns>
/// <exception cref="InvalidOperationException">Manager is not running. Call <see cref="Start()"/></exception>
public NetPeer Connect(IPEndPoint target, NetDataWriter connectionData)
{
if (!_socket.IsRunning)
throw new InvalidOperationException("Client is not running");
NetPeer peer;
byte connectionNumber = 0;
lock(_requestsDict)
{
if (_requestsDict.ContainsKey(target))
return null;
}
_peersLock.EnterUpgradeableReadLock();
if (_peersDict.TryGetValue(target, out peer))
{
switch (peer.ConnectionState)
{
//just return already connected peer
case ConnectionState.Connected:
case ConnectionState.Outgoing:
_peersLock.ExitUpgradeableReadLock();
return peer;
}
//else reconnect
connectionNumber = (byte)((peer.ConnectionNum + 1) % NetConstants.MaxConnectionNumber);
RemovePeer(peer);
}
//Create reliable connection
//And send connection request
peer = new NetPeer(this, target, GetNextPeerId(), connectionNumber, connectionData);
AddPeer(peer);
_peersLock.ExitUpgradeableReadLock();
return peer;
}
/// <summary>
/// Force closes connection and stop all threads.
/// </summary>
public void Stop()
{
Stop(true);
}
/// <summary>
/// Force closes connection and stop all threads.
/// </summary>
/// <param name="sendDisconnectMessages">Send disconnect messages</param>
public void Stop(bool sendDisconnectMessages)
{
if (!_socket.IsRunning)
return;
NetDebug.Write("[NM] Stop");
//Send last disconnect
for(var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
netPeer.Shutdown(null, 0, 0, !sendDisconnectMessages);
//Stop
_socket.Close(false);
_updateTriggerEvent.Set();
_logicThread.Join();
_logicThread = null;
//clear peers
_peersLock.EnterWriteLock();
_headPeer = null;
_peersDict.Clear();
_peersArray = new NetPeer[32];
_peersLock.ExitWriteLock();
lock(_peerIds)
_peerIds.Clear();
#if DEBUG
lock (_pingSimulationList)
_pingSimulationList.Clear();
#endif
_connectedPeersCount = 0;
lock(_netEventsQueue)
_netEventsQueue.Clear();
}
/// <summary>
/// Return peers count with connection state
/// </summary>
/// <param name="peerState">peer connection state (you can use as bit flags)</param>
/// <returns>peers count</returns>
public int GetPeersCount(ConnectionState peerState)
{
int count = 0;
_peersLock.EnterReadLock();
for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
{
if ((netPeer.ConnectionState & peerState) != 0)
count++;
}
_peersLock.ExitReadLock();
return count;
}
/// <summary>
/// Get copy of peers (without allocations)
/// </summary>
/// <param name="peers">List that will contain result</param>
/// <param name="peerState">State of peers</param>
public void GetPeersNonAlloc(List<NetPeer> peers, ConnectionState peerState)
{
peers.Clear();
_peersLock.EnterReadLock();
for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
{
if ((netPeer.ConnectionState & peerState) != 0)
peers.Add(netPeer);
}
_peersLock.ExitReadLock();
}
/// <summary>
/// Disconnect all peers without any additional data
/// </summary>
public void DisconnectAll()
{
DisconnectAll(null, 0, 0);
}
/// <summary>
/// Disconnect all peers with shutdown message
/// </summary>
/// <param name="data">Data to send (must be less or equal MTU)</param>
/// <param name="start">Data start</param>
/// <param name="count">Data count</param>
public void DisconnectAll(byte[] data, int start, int count)
{
//Send disconnect packets
_peersLock.EnterReadLock();
for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
{
DisconnectPeer(
netPeer,
DisconnectReason.DisconnectPeerCalled,
0,
false,
data,
start,
count,
null);
}
_peersLock.ExitReadLock();
}
/// <summary>
/// Immediately disconnect peer from server without additional data
/// </summary>
/// <param name="peer">peer to disconnect</param>
public void DisconnectPeerForce(NetPeer peer)
{
DisconnectPeerForce(peer, DisconnectReason.DisconnectPeerCalled, 0, null);
}
/// <summary>
/// Disconnect peer from server
/// </summary>
/// <param name="peer">peer to disconnect</param>
public void DisconnectPeer(NetPeer peer)
{
DisconnectPeer(peer, null, 0, 0);
}
/// <summary>
/// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8)
/// </summary>
/// <param name="peer">peer to disconnect</param>
/// <param name="data">additional data</param>
public void DisconnectPeer(NetPeer peer, byte[] data)
{
DisconnectPeer(peer, data, 0, data.Length);
}
/// <summary>
/// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8)
/// </summary>
/// <param name="peer">peer to disconnect</param>
/// <param name="writer">additional data</param>
public void DisconnectPeer(NetPeer peer, NetDataWriter writer)
{
DisconnectPeer(peer, writer.Data, 0, writer.Length);
}
/// <summary>
/// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8)
/// </summary>
/// <param name="peer">peer to disconnect</param>
/// <param name="data">additional data</param>
/// <param name="start">data start</param>
/// <param name="count">data length</param>
public void DisconnectPeer(NetPeer peer, byte[] data, int start, int count)
{
DisconnectPeer(
peer,
DisconnectReason.DisconnectPeerCalled,
0,
false,
data,
start,
count,
null);
}
public NetPeerEnumerator GetEnumerator()
{
return new NetPeerEnumerator(_headPeer);
}
IEnumerator<NetPeer> IEnumerable<NetPeer>.GetEnumerator()
{
return new NetPeerEnumerator(_headPeer);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new NetPeerEnumerator(_headPeer);
}
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/NetManager.cs.meta
================================================
fileFormatVersion: 2
guid: 58e96e53edef5bc4ea934b50d4d4c8ba
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/NetPacket.cs
================================================
using System;
using System.Net;
using LiteNetLib.Utils;
namespace LiteNetLib
{
internal enum PacketProperty : byte
{
Unreliable,
Channeled,
Ack,
Ping,
Pong,
ConnectRequest,
ConnectAccept,
Disconnect,
UnconnectedMessage,
MtuCheck,
MtuOk,
Broadcast,
Merged,
ShutdownOk,
PeerNotFound,
InvalidProtocol,
NatMessage,
Empty
}
internal sealed class NetPacket
{
private static readonly int LastProperty = Enum.GetValues(typeof(PacketProperty)).Length;
private static readonly int[] HeaderSizes;
static NetPacket()
{
HeaderSizes = new int[LastProperty+1];
for (int i = 0; i < HeaderSizes.Length; i++)
{
switch ((PacketProperty)i)
{
case PacketProperty.Channeled:
case PacketProperty.Ack:
HeaderSizes[i] = NetConstants.ChanneledHeaderSize;
break;
case PacketProperty.Ping:
HeaderSizes[i] = NetConstants.HeaderSize + 2;
break;
case PacketProperty.ConnectRequest:
HeaderSizes[i] = NetConnectRequestPacket.HeaderSize;
break;
case PacketProperty.ConnectAccept:
HeaderSizes[i] = NetConnectAcceptPacket.Size;
break;
case PacketProperty.Disconnect:
HeaderSizes[i] = NetConstants.HeaderSize + 8;
break;
case PacketProperty.Pong:
HeaderSizes[i] = NetConstants.HeaderSize + 10;
break;
default:
HeaderSizes[i] = NetConstants.HeaderSize;
break;
}
}
}
//Header
public PacketProperty Property
{
get { return (PacketProperty)(RawData[0] & 0x1F); }
set { RawData[0] = (byte)((RawData[0] & 0xE0) | (byte)value); }
}
public byte ConnectionNumber
{
get { return (byte)((RawData[0] & 0x60) >> 5); }
set { RawData[0] = (byte) ((RawData[0] & 0x9F) | (value << 5)); }
}
public ushort Sequence
{
get { return BitConverter.ToUInt16(RawData, 1); }
set { FastBitConverter.GetBytes(RawData, 1, value); }
}
public bool IsFragmented
{
get { return (RawData[0] & 0x80) != 0; }
}
public void MarkFragmented()
{
RawData[0] |= 0x80; //set first bit
}
public byte ChannelId
{
get { return RawData[3]; }
set { RawData[3] = value; }
}
public ushort FragmentId
{
get { return BitConverter.ToUInt16(RawData, 4); }
set { FastBitConverter.GetBytes(RawData, 4, value); }
}
public ushort FragmentPart
{
get { return BitConverter.ToUInt16(RawData, 6); }
set { FastBitConverter.GetBytes(RawData, 6, value); }
}
public ushort FragmentsTotal
{
get { return BitConverter.ToUInt16(RawData, 8); }
set { FastBitConverter.GetBytes(RawData, 8, value); }
}
//Data
public byte[] RawData;
public int Size;
//Delivery
public object UserData;
//Pool node
public NetPacket Next;
public NetPacket(int size)
{
RawData = new byte[size];
Size = size;
}
public NetPacket(PacketProperty property, int size)
{
size += GetHeaderSize(property);
RawData = new byte[size];
Property = property;
Size = size;
}
public static int GetHeaderSize(PacketProperty property)
{
return HeaderSizes[(int)property];
}
public int GetHeaderSize()
{
return HeaderSizes[RawData[0] & 0x1F];
}
//Packet constructor from byte array
public bool FromBytes(byte[] data, int start, int packetSize)
{
//Reading property
byte property = (byte)(data[start] & 0x1F);
bool fragmented = (data[start] & 0x80) != 0;
int headerSize = HeaderSizes[property];
if (property > LastProperty || packetSize < headerSize ||
(fragmented && packetSize < headerSize + NetConstants.FragmentHeaderSize) ||
data.Length < start + packetSize)
{
return false;
}
Buffer.BlockCopy(data, start, RawData, 0, packetSize);
Size = (ushort)packetSize;
return true;
}
}
internal sealed class NetConnectRequestPacket
{
public const int HeaderSize = 14;
public readonly long ConnectionTime;
public readonly byte ConnectionNumber;
public readonly byte[] TargetAddress;
public readonly NetDataReader Data;
private NetConnectRequestPacket(long connectionTime, byte connectionNumber, byte[] targetAddress, NetDataReader data)
{
ConnectionTime = connectionTime;
ConnectionNumber = connectionNumber;
TargetAddress = targetAddress;
Data = data;
}
public static int GetProtocolId(NetPacket packet)
{
return BitConverter.ToInt32(packet.RawData, 1);
}
public static NetConnectRequestPacket FromData(NetPacket packet)
{
if (packet.ConnectionNumber >= NetConstants.MaxConnectionNumber)
return null;
//Getting new id for peer
long connectionId = BitConverter.ToInt64(packet.RawData, 5);
//Get target address
int addrSize = packet.RawData[13];
if (addrSize != 16 && addrSize != 28)
return null;
byte[] addressBytes = new byte[addrSize];
Buffer.BlockCopy(packet.RawData, 14, addressBytes, 0, addrSize);
// Read data and create request
var reader = new NetDataReader(null, 0, 0);
if (packet.Size > HeaderSize+addrSize)
reader.SetSource(packet.RawData, HeaderSize + addrSize, packet.Size);
return new NetConnectRequestPacket(connectionId, packet.ConnectionNumber, addressBytes, reader);
}
public static NetPacket Make(NetDataWriter connectData, SocketAddress addressBytes, long connectId)
{
//Make initial packet
var packet = new NetPacket(PacketProperty.ConnectRequest, connectData.Length+addressBytes.Size);
//Add data
FastBitConverter.GetBytes(packet.RawData, 1, NetConstants.ProtocolId);
FastBitConverter.GetBytes(packet.RawData, 5, connectId);
packet.RawData[13] = (byte)addressBytes.Size;
for (int i = 0; i < addressBytes.Size; i++)
packet.RawData[14+i] = addressBytes[i];
Buffer.BlockCopy(connectData.Data, 0, packet.RawData, 14+addressBytes.Size, connectData.Length);
return packet;
}
}
internal sealed class NetConnectAcceptPacket
{
public const int Size = 11;
public readonly long ConnectionId;
public readonly byte ConnectionNumber;
public readonly bool IsReusedPeer;
private NetConnectAcceptPacket(long connectionId, byte connectionNumber, bool isReusedPeer)
{
ConnectionId = connectionId;
ConnectionNumber = connectionNumber;
IsReusedPeer = isReusedPeer;
}
public static NetConnectAcceptPacket FromData(NetPacket packet)
{
if (packet.Size > Size)
return null;
long connectionId = BitConverter.ToInt64(packet.RawData, 1);
//check connect num
byte connectionNumber = packet.RawData[9];
if (connectionNumber >= NetConstants.MaxConnectionNumber)
return null;
//check reused flag
byte isReused = packet.RawData[10];
if (isReused > 1)
return null;
return new NetConnectAcceptPacket(connectionId, connectionNumber, isReused == 1);
}
public static NetPacket Make(long connectId, byte connectNum, bool reusedPeer)
{
var packet = new NetPacket(PacketProperty.ConnectAccept, 0);
FastBitConverter.GetBytes(packet.RawData, 1, connectId);
packet.RawData[9] = connectNum;
packet.RawData[10] = (byte)(reusedPeer ? 1 : 0);
return packet;
}
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/NetPacket.cs.meta
================================================
fileFormatVersion: 2
guid: 7522936b42c769445b2f5d3d2558f5ed
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/NetPacketPool.cs
================================================
using System;
using System.Threading;
namespace LiteNetLib
{
internal sealed class NetPacketPool
{
private NetPacket _head;
private int _count;
public NetPacket GetWithData(PacketProperty property, byte[] data, int start, int length)
{
int headerSize = NetPacket.GetHeaderSize(property);
NetPacket packet = GetPacket(length + headerSize);
packet.Property = property;
Buffer.BlockCopy(data, start, packet.RawData, headerSize, length);
return packet;
}
//Get packet with size
public NetPacket GetWithProperty(PacketProperty property, int size)
{
NetPacket packet = GetPacket(size + NetPacket.GetHeaderSize(property));
packet.Property = property;
return packet;
}
public NetPacket GetWithProperty(PacketProperty property)
{
NetPacket packet = GetPacket(NetPacket.GetHeaderSize(property));
packet.Property = property;
return packet;
}
public NetPacket GetPacket(int size)
{
if (size > NetConstants.MaxPacketSize)
return new NetPacket(size);
NetPacket packet;
do
{
packet = _head;
if (packet == null)
return new NetPacket(size);
} while (packet != Interlocked.CompareExchange(ref _head, packet.Next, packet));
_count--;
packet.Size = size;
if (packet.RawData.Length < size)
packet.RawData = new byte[size];
return packet;
}
public void Recycle(NetPacket packet)
{
if (packet.RawData.Length > NetConstants.MaxPacketSize || _count >= NetConstants.PacketPoolSize)
{
//Don't pool big packets. Save memory
return;
}
_count++;
//Clean fragmented flag
packet.RawData[0] = 0;
do
{
packet.Next = _head;
} while (packet.Next != Interlocked.CompareExchange(ref _head, packet, packet.Next));
}
}
}
================================================
FILE: Assets/Plugins/LiteNetLib/NetPacketPool.cs.meta
================================================
fileFormatVersion: 2
guid: 779e0db7afc7c6e4eb88b849e7c3eced
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
================================================
FILE: Assets/Plugins/LiteNetLib/NetPeer.cs
================================================
#if DEBUG
#define STATS_ENABLED
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading;
using LiteNetLib.Utils;
namespace LiteNetLib
{
/// <summary>
/// Peer connection state
/// </summary>
[Flags]
public enum ConnectionState : byte
{
Outgoing = 1 << 1,
Connected = 1 << 2,
ShutdownRequested = 1 << 3,
Disconnected = 1 << 4,
Any = Outgoing | Connected | ShutdownRequested
}
internal enum ConnectRequestResult
{
None,
P2PLose, //when peer connecting
Reconnection, //when peer was connected
NewConnection //when peer was disconnected
}
internal enum DisconnectResult
{
None,
Reject,
Disconnect
}
internal enum ShutdownResult
{
None,
Success,
WasConnected
}
/// <summary>
/// Network peer. Main purpose is sending messages to specific peer.
/// </summary>
public class NetPeer
{
//Ping and RTT
private int _rtt;
private int _avgRtt;
private int _rttCount;
private double _resendDelay = 27.0;
private int _pingSendTimer;
private int _rttResetTimer;
private readonly Stopwatch _pingTimer = new Stopwatch();
private int _timeSinceLastPacket;
private long _remoteDelta;
//Common
private readonly NetPacketPool _packetPool;
private readonly object _shutdownLock = new object();
internal volatile NetPeer NextPeer;
internal NetPeer PrevPeer;
internal byte ConnectionNum
{
get { return _connectNum; }
private set
{
_connectNum = value;
_mergeData.ConnectionNumber = value;
_pingPacket.ConnectionNumber = value;
_pongPacket.ConnectionNumber = value;
}
}
//Channels
private readonly Queue<NetPacket> _unreliableChannel;
private readonly BaseChannel[] _channels;
private BaseChannel _headChannel;
//MTU
private int _mtu;
private int _mtuIdx;
private bool _finishMtu;
private int _mtuCheckTimer;
private int _mtuCheckAttempts;
private const int MtuCheckDelay = 1000;
private const int MaxMtuCheckAttempts = 4;
private readonly object _mtuMutex = new object();
//Fragment
private class IncomingFragments
{
public NetPacket[] Fragments;
public int ReceivedCount;
public int TotalSize;
public byte ChannelId;
}
private int _fragmentId;
private readonly Dictionary<ushort, IncomingFragments> _holdedFragments;
private readonly Dictionary<ushort, ushort> _deliveredFragments;
//Merging
private readonly NetPacket _mergeData;
private int _mergePos;
private int _mergeCount;
//Connection
private int _connectAttempts;
private int _connectTimer;
private long _connectTime;
private byte _connectNum;
private ConnectionState _connectionState;
private NetPacket _shutdownPacket;
private const int ShutdownDelay = 300;
private int _shutdownTimer;
private readonly NetPacket _pingPacket;
private readonly NetPacket _pongPacket;
private readonly NetPacket _connectRequestPacket;
private readonly NetPacket _connectAcceptPacket;
/// <summary>
/// Peer ip address and port
/// </summary>
public readonly IPEndPoint EndPoint;
/// <summary>
/// Peer parent NetManager
/// </summary>
public readonly NetManager NetManager;
/// <summary>
/// Current connection state
/// </summary>
public ConnectionState ConnectionState { get { return _connectionState; } }
/// <summary>
/// Connection time for internal purposes
/// </summary>
internal long ConnectTime { get { return _connectTime; } }
/// <summary>
/// Peer id can be used as key in your dictionary of peers
/// </summary>
public readonly int Id;
/// <summary>
/// Current ping in milliseconds
/// </summary>
public int Ping { get { return _avgRtt/2; } }
/// <summary>
/// Current MTU - Maximum Transfer Unit ( maximum udp packet size without fragmentation )
/// </summary>
public int Mtu { get { return _mtu; } }
/// <summary>
/// Delta with remote time in ticks (not accurate)
/// positive - remote time > our time
/// </summary>
public long RemoteTimeDelta
{
get { return _remoteDelta; }
}
/// <summary>
/// Remote UTC time (not accurate)
/// </summary>
public DateTime RemoteUtcTime
{
get { return new DateTime(DateTime.UtcNow.Ticks + _remoteDelta); }
}
/// <summary>
/// Time since last packet received (including internal library packets)
/// </summary>
public int TimeSinceLastPacket { get { return _timeSinceLastPacket; } }
internal double ResendDelay { get { return _resendDelay; } }
/// <summary>
/// Application defined object containing data about the connection
/// </summary>
public object Tag;
/// <summary>
/// Statistics of peer connection
/// </summary>
public readonly NetStatistics Statistics;
//incoming connection constructor
internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int id)
{
Id = id;
Statistics = new NetStatistics();
_packetPool = netManager.NetPacketPool;
NetManager = netManager;
SetMtu(0);
EndPoint = remoteEndPoint;
_connectionState = ConnectionState.Connected;
_mergeData = new NetPacket(PacketProperty.Merged, NetConstants.MaxPacketSize);
_pongPacket = new NetPacket(PacketProperty.Pong, 0);
_pingPacket = new NetPacket(PacketProperty.Ping, 0) {Sequence = 1};
_unreliableChannel = new Queue<NetPacket>(64);
_headChannel = null;
_holdedFragments = new Dictionary<ushort, IncomingFragments>();
_deliveredFragments = new Dictionary<ushort, ushort>();
_channels = new BaseChannel[netManager.ChannelsCount * 4];
}
private void SetMtu(int mtuIdx)
{
_mtu = NetConstants.PossibleMtu[mtuIdx] - NetManager.ExtraPacketSizeForLayer;
}
/// <summary>
/// Returns packets count in queue for reliable channel
/// </summary>
/// <param name="channelNumber">number of channel 0-63</param>
/// <param name="ordered">type of channel ReliableOrdered or ReliableUnordered</param>
/// <returns>packets count in channel queue</returns>
public int GetPacketsCountInReliableQueue(byte channelNumber, bool ordered)
{
int idx = channelNumber * 4 +
(byte) (ordered ? DeliveryMethod.ReliableOrdered : DeliveryMethod.ReliableUnordered);
var channel = _channels[idx];
return channel != null ? ((ReliableChannel)channel).PacketsInQueue : 0;
}
private BaseChannel CreateChannel(byte idx)
{
BaseChannel newChannel = _channels[idx];
if (newChannel != null)
return newChannel;
switch ((DeliveryMethod)(idx % 4))
{
case DeliveryMethod.ReliableUnordered:
newChannel = new ReliableChannel(this, false, idx);
break;
case DeliveryMethod.Sequenced:
newChannel = new SequencedChannel(this, false, idx);
break;
case DeliveryMethod.ReliableOrdered:
newChannel = new ReliableChannel(this, true, idx);
break;
case DeliveryMethod.ReliableSequenced:
newChannel = new SequencedChannel(this, true, idx);
break;
}
BaseChannel prevChannel = Interlocked.CompareExchange(ref _channels[idx], newChannel, null);
if (prevChannel != null)
return prevChannel;
BaseChannel headChannel;
do
{
headChannel = _headChannel;
newChannel.Next = headChannel;
}
while (Interlocked.CompareExchange(ref _headChannel, newChannel, headChannel) != headChannel);
return newChannel;
}
//"Connect to" constructor
internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int id, byte connectNum, NetDataWriter connectData)
: this(netManager, remoteEndPoint, id)
{
_connectTime = DateTime.UtcNow.Ticks;
_connectionState = ConnectionState.Outgoing;
ConnectionNum = connectNum;
//Make initial packet
_connectRequestPacket = NetConnectRequestPacket.Make(connectData, remoteEndPoint.Serialize(), _connectTime);
_connectRequestPacket.ConnectionNumber = connectNum;
//Send request
NetManager.SendRaw(_connectRequestPacket, EndPoint);
NetDebug.Write(NetLogLevel.Trace, "[CC] ConnectId: {0}, ConnectNum: {1}", _connectTime, connectNum);
}
//"Accept" incoming constructor
internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int id, long connectId, byte connectNum)
: this(netManager, remoteEndPoint, id)
{
_connectTime = connectId;
_connectionState = ConnectionState.Connected;
ConnectionNum = connectNum;
//Make initial packet
_connectAcceptPacket = NetConnectAcceptPacket.Make(_connectTime, connectNum, false);
//Send
NetManager.SendRaw(_connectAcceptPacket, EndPoint);
NetDebug.Write(NetLogLevel.Trace, "[CC] ConnectId: {0}", _connectTime);
}
//Reject
internal void Reject(long connectionId, byte connectionNumber, byte[] data, int start, int length)
{
_connectTime = connectionId;
_connectNum = connectionNumber;
Shutdown(data, start, length, false);
}
internal bool ProcessConnectAccept(NetConnectAcceptPacket packet)
{
if (_connectionState != ConnectionState.Outgoing)
return false;
//check connection id
if (packet.ConnectionId != _connectTime)
{
NetDebug.Write(NetLogLevel.Trace, "[NC] Invalid connectId: {0}", _connectTime);
return false;
}
//check connect num
ConnectionNum = packet.ConnectionNumber;
NetDebug.Write(NetLogLevel.Trace, "[NC] Received connection accept");
Interlocked.Exchange(ref _timeSinceLastPacket, 0);
_connectionState = ConnectionState.Connected;
return true;
}
/// <summary>
/// Gets maximum size of packet that will be not fragmented.
/// </summary>
/// <param name="options">Type of packet that you want send</param>
/// <returns>size in bytes</returns>
public int GetMaxSinglePacketSize(DeliveryMethod options)
{
return _mtu - NetPacket.GetHeaderSize(options == DeliveryMethod.Unreliable ? PacketProperty.Unreliable : PacketProperty.Channeled);
}
/// <summary>
/// Send data to peer with delivery event called
/// </summary>
/// <param name="data">Data</param>
/// <param name="channelNumber">Number of channel (from 0 to channelsCount - 1)</param>
/// <param name="deliveryMethod">Delivery method (reliable, unreliable, etc.)</param>
/// <param name="userData">User data that will be received in DeliveryEvent</param>
/// <exception cref="ArgumentException">
/// If you trying to send unreliable packet type<para/>
/// </exception>
public void SendWithDeliveryEvent(byte[] data, byte channelNumber, DeliveryMethod deliveryMethod, object userData)
{
if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered)
throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets");
SendInternal(data, 0, data.Length, channelNumber, deliveryMethod, userData);
}
/// <summary>
/// Send data to peer with delivery event called
/// </summary>
/// <param name="data">Data</param>
/// <param name="start">Start of data</param>
/// <param name="length">Length of data</param>
/// <param name="channelNumber">Number of channel (from 0 to channelsCount - 1)</param>
/// <param name="deliveryMethod">Delivery method (reliable, unreliable, etc.)</param>
/// <param name="userData">User data that will be received in DeliveryEvent</param>
/// <exception cref="ArgumentException">
/// If you trying to send unreliable packet type<para/>
/// </exception>
public void SendWithDeliveryEvent(byte[] data, int start, int length, byte channelNumber, DeliveryMethod deliveryMethod, object userData)
{
if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered)
throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets");
SendInternal(data, start, length, channelNumber, deliveryMethod, userData);
}
/// <summary>
/// Send data to peer with delivery event called
/// </summary>
/// <param name="dataWriter">Data</param>
/// <param name="channelNumber">Number of channel (from 0 to channelsCount - 1)</param>
/// <param name="deliveryMethod">Delivery method (reliable, unreliable, etc.)</param>
/// <param name="userData">User data that will be received in DeliveryEvent</param>
/// <exception cref="ArgumentException">
/// If you trying to send unreliable packet type<para/>
/// </exception>
public void SendWithDeliveryEvent(NetDataWriter dataWriter, byte channelNumber, DeliveryMethod deliveryMethod, object userData)
{
if (deliveryMethod != DeliveryMethod.ReliableOrdered && deliveryMethod != DeliveryMethod.ReliableUnordered)
throw new ArgumentException("Delivery event will work only for ReliableOrdered/Unordered packets");
SendInternal(dataWriter.Data, 0, dataWriter.Length, channelNumber, deliveryMethod, userData);
}
/// <summary>
/// Send data to peer (channel - 0)
/// </summary>
/// <param name="data">Data</param>
/// <param name="deliveryMethod">Send options (reliable, unreliable, etc.)</param>
/// <exception cref="TooBigPacketException">
/// If size exceeds maximum limit:<para/>
/// MTU - headerSize bytes for Unreliable<para/>
/// Fragment count exceeded ushort.MaxValue<para/>
/// </exception>
public void Send(byte[] data, DeliveryMethod deliveryMethod)
{
SendInternal(data, 0, data.Length, 0, deliveryMethod, null);
}
/// <summary>
/// Send data to peer (channel - 0)
/// </summary>
/// <param name="dataWriter">DataWriter with data</param>
/// <param name="deliveryMethod">Send options (reliable, unreliable, etc.)</param>
/// <exception cref="TooBigPacketException">
/// If size exceeds maximum limit:<para/>
/// MTU - headerSize bytes for Unreliable<para/>
/// Fragment count exceeded ushort.MaxValue<para/>
/// </exception>
public void Send(NetDataWriter dataWriter, DeliveryMethod deliveryMethod)
{
SendInternal(dataWriter.Data, 0, dataWriter.Length, 0, deliveryMethod, null);
}
/// <summary>
/// Send data to peer (channel - 0)
/// </summary>
/// <param name="data">Data</param>
/// <param name="start">Start of data</param>
/// <param name="length">Length of data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <exception cref="TooBigPacketException">
/// If size exceeds maximum limit:<para/>
/// MTU - headerSize bytes for Unreliable<para/>
/// Fragment count exceeded ushort.MaxValue<para/>
/// </exception>
public void Send(byte[] data, int start, int length, DeliveryMethod options)
{
SendInternal(data, start, length, 0, options, null);
}
gitextract_i90u_vd7/ ├── .gitignore ├── .vscode/ │ └── settings.json ├── Assets/ │ ├── Code/ │ │ ├── Client/ │ │ │ ├── ClientLogic.cs │ │ │ ├── ClientLogic.cs.meta │ │ │ ├── ClientPlayer.cs │ │ │ ├── ClientPlayer.cs.meta │ │ │ ├── ClientPlayerManager.cs │ │ │ ├── ClientPlayerManager.cs.meta │ │ │ ├── ClientPlayerView.cs │ │ │ ├── ClientPlayerView.cs.meta │ │ │ ├── IPlayerView.cs │ │ │ ├── IPlayerView.cs.meta │ │ │ ├── RemotePlayer.cs │ │ │ ├── RemotePlayer.cs.meta │ │ │ ├── RemotePlayerView.cs │ │ │ ├── RemotePlayerView.cs.meta │ │ │ ├── ShootEffect.cs │ │ │ ├── ShootEffect.cs.meta │ │ │ ├── UiController.cs │ │ │ └── UiController.cs.meta │ │ ├── Client.meta │ │ ├── Server/ │ │ │ ├── AntilagSystem.cs │ │ │ ├── AntilagSystem.cs.meta │ │ │ ├── ServerLogic.cs │ │ │ ├── ServerLogic.cs.meta │ │ │ ├── ServerPlayer.cs │ │ │ ├── ServerPlayer.cs.meta │ │ │ ├── ServerPlayerManager.cs │ │ │ └── ServerPlayerManager.cs.meta │ │ ├── Server.meta │ │ ├── Shared/ │ │ │ ├── BasePlayer.cs │ │ │ ├── BasePlayer.cs.meta │ │ │ ├── BasePlayerManager.cs │ │ │ ├── BasePlayerManager.cs.meta │ │ │ ├── Collisions.cs │ │ │ ├── Collisions.cs.meta │ │ │ ├── Extensions.cs │ │ │ ├── Extensions.cs.meta │ │ │ ├── GamePackets.cs │ │ │ ├── GamePackets.cs.meta │ │ │ ├── GamePool.cs │ │ │ ├── GamePool.cs.meta │ │ │ ├── GameTimer.cs │ │ │ ├── GameTimer.cs.meta │ │ │ ├── LiteRingBuffer.cs │ │ │ ├── LiteRingBuffer.cs.meta │ │ │ ├── LogicTimer.cs │ │ │ ├── LogicTimer.cs.meta │ │ │ ├── NetworkGeneral.cs │ │ │ └── NetworkGeneral.cs.meta │ │ └── Shared.meta │ ├── Code.meta │ ├── Materials/ │ │ ├── ShootEffectMat.mat │ │ └── ShootEffectMat.mat.meta │ ├── Materials.meta │ ├── Plugins/ │ │ ├── LiteNetLib/ │ │ │ ├── BaseChannel.cs │ │ │ ├── BaseChannel.cs.meta │ │ │ ├── ConnectionRequest.cs │ │ │ ├── ConnectionRequest.cs.meta │ │ │ ├── INetEventListener.cs │ │ │ ├── INetEventListener.cs.meta │ │ │ ├── Layers/ │ │ │ │ ├── Crc32cLayer.cs │ │ │ │ ├── Crc32cLayer.cs.meta │ │ │ │ ├── PacketLayerBase.cs │ │ │ │ ├── PacketLayerBase.cs.meta │ │ │ │ ├── XorEncryptLayer.cs │ │ │ │ └── XorEncryptLayer.cs.meta │ │ │ ├── Layers.meta │ │ │ ├── NatPunchModule.cs │ │ │ ├── NatPunchModule.cs.meta │ │ │ ├── NetConstants.cs │ │ │ ├── NetConstants.cs.meta │ │ │ ├── NetDebug.cs │ │ │ ├── NetDebug.cs.meta │ │ │ ├── NetManager.cs │ │ │ ├── NetManager.cs.meta │ │ │ ├── NetPacket.cs │ │ │ ├── NetPacket.cs.meta │ │ │ ├── NetPacketPool.cs │ │ │ ├── NetPacketPool.cs.meta │ │ │ ├── NetPeer.cs │ │ │ ├── NetPeer.cs.meta │ │ │ ├── NetSocket.cs │ │ │ ├── NetSocket.cs.meta │ │ │ ├── NetStatistics.cs │ │ │ ├── NetStatistics.cs.meta │ │ │ ├── NetUtils.cs │ │ │ ├── NetUtils.cs.meta │ │ │ ├── ReliableChannel.cs │ │ │ ├── ReliableChannel.cs.meta │ │ │ ├── SequencedChannel.cs │ │ │ ├── SequencedChannel.cs.meta │ │ │ ├── Utils/ │ │ │ │ ├── CRC32C.cs │ │ │ │ ├── CRC32C.cs.meta │ │ │ │ ├── FastBitConverter.cs │ │ │ │ ├── FastBitConverter.cs.meta │ │ │ │ ├── INetSerializable.cs │ │ │ │ ├── INetSerializable.cs.meta │ │ │ │ ├── NetDataReader.cs │ │ │ │ ├── NetDataReader.cs.meta │ │ │ │ ├── NetDataWriter.cs │ │ │ │ ├── NetDataWriter.cs.meta │ │ │ │ ├── NetPacketProcessor.cs │ │ │ │ ├── NetPacketProcessor.cs.meta │ │ │ │ ├── NetSerializer.cs │ │ │ │ ├── NetSerializer.cs.meta │ │ │ │ ├── NtpPacket.cs │ │ │ │ ├── NtpPacket.cs.meta │ │ │ │ ├── NtpRequest.cs │ │ │ │ └── NtpRequest.cs.meta │ │ │ └── Utils.meta │ │ └── LiteNetLib.meta │ ├── Plugins.meta │ ├── Prefabs/ │ │ ├── ClientPlayerPrefab.prefab │ │ ├── ClientPlayerPrefab.prefab.meta │ │ ├── RemotePlayerPrefab.prefab │ │ ├── RemotePlayerPrefab.prefab.meta │ │ ├── ShootEffect.prefab │ │ └── ShootEffect.prefab.meta │ ├── Prefabs.meta │ ├── Scenes/ │ │ ├── SampleScene.unity │ │ └── SampleScene.unity.meta │ ├── Scenes.meta │ ├── Sounds/ │ │ ├── death1.ogg │ │ ├── death1.ogg.meta │ │ ├── death2.ogg │ │ ├── death2.ogg.meta │ │ ├── death3.ogg │ │ ├── death3.ogg.meta │ │ ├── hit1.ogg │ │ ├── hit1.ogg.meta │ │ ├── hit2.ogg │ │ ├── hit2.ogg.meta │ │ ├── hit3.ogg │ │ ├── hit3.ogg.meta │ │ ├── shoot1.ogg │ │ ├── shoot1.ogg.meta │ │ ├── shoot2.ogg │ │ ├── shoot2.ogg.meta │ │ ├── shoot3.ogg │ │ └── shoot3.ogg.meta │ └── Sounds.meta ├── LICENSE ├── Packages/ │ ├── manifest.json │ └── packages-lock.json ├── ProjectSettings/ │ ├── AudioManager.asset │ ├── ClusterInputManager.asset │ ├── DynamicsManager.asset │ ├── EditorBuildSettings.asset │ ├── EditorSettings.asset │ ├── GraphicsSettings.asset │ ├── InputManager.asset │ ├── MemorySettings.asset │ ├── NavMeshAreas.asset │ ├── NetworkManager.asset │ ├── PackageManagerSettings.asset │ ├── Physics2DSettings.asset │ ├── PresetManager.asset │ ├── ProjectSettings.asset │ ├── ProjectVersion.txt │ ├── QualitySettings.asset │ ├── TagManager.asset │ ├── TimeManager.asset │ ├── UnityConnectSettings.asset │ ├── VFXManager.asset │ ├── VersionControlSettings.asset │ ├── XRSettings.asset │ └── boot.config └── README.md
SYMBOL INDEX (828 symbols across 50 files)
FILE: Assets/Code/Client/ClientLogic.cs
class ClientLogic (line 13) | public class ClientLogic : MonoBehaviour, INetEventListener
method ShootEffectContructor (line 38) | private ShootEffect ShootEffectContructor()
method Awake (line 45) | private void Awake()
method OnLogicUpdate (line 70) | private void OnLogicUpdate()
method Update (line 75) | private void Update()
method OnDestroy (line 89) | private void OnDestroy()
method OnPlayerJoined (line 94) | private void OnPlayerJoined(PlayerJoinedPacket packet)
method OnServerState (line 102) | private void OnServerState()
method OnShoot (line 111) | private void OnShoot()
method SpawnShoot (line 119) | public void SpawnShoot(Vector2 from, Vector2 to)
method OnPlayerLeaved (line 125) | private void OnPlayerLeaved(PlayerLeavedPacket packet)
method OnJoinAccept (line 132) | private void OnJoinAccept(JoinAcceptPacket packet)
method SendPacketSerializable (line 141) | public void SendPacketSerializable<T>(PacketType type, T packet, Deliv...
method SendPacket (line 151) | public void SendPacket<T>(T packet, DeliveryMethod deliveryMethod) whe...
method OnPeerConnected (line 161) | void INetEventListener.OnPeerConnected(NetPeer peer)
method OnPeerDisconnected (line 170) | void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo...
method OnNetworkError (line 183) | void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError...
method OnNetworkReceive (line 188) | void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader ...
method OnNetworkReceiveUnconnected (line 215) | void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEn...
method OnNetworkLatencyUpdate (line 221) | void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency)
method OnConnectionRequest (line 226) | void INetEventListener.OnConnectionRequest(ConnectionRequest request)
method Connect (line 231) | public void Connect(string ip, Action<DisconnectInfo> onDisconnected)
FILE: Assets/Code/Client/ClientPlayer.cs
class ClientPlayer (line 7) | public class ClientPlayer : BasePlayer
method ClientPlayer (line 23) | public ClientPlayer(ClientLogic clientLogic, ClientPlayerManager manag...
method ReceiveServerState (line 30) | public void ReceiveServerState(ServerState serverState, PlayerState ou...
method Spawn (line 74) | public override void Spawn(Vector2 position)
method SetInput (line 79) | public void SetInput(Vector2 velocity, float rotation, bool fire)
method Update (line 97) | public override void Update(float delta)
FILE: Assets/Code/Client/ClientPlayerManager.cs
type PlayerHandler (line 7) | public struct PlayerHandler
method PlayerHandler (line 12) | public PlayerHandler(BasePlayer player, IPlayerView view)
method Update (line 18) | public void Update(float delta)
class ClientPlayerManager (line 24) | public class ClientPlayerManager : BasePlayerManager
method ClientPlayerManager (line 33) | public ClientPlayerManager(ClientLogic clientLogic)
method GetEnumerator (line 39) | public override IEnumerator<BasePlayer> GetEnumerator()
method ApplyServerState (line 45) | public void ApplyServerState(ref ServerState serverState)
method OnShoot (line 65) | public override void OnShoot(BasePlayer from, Vector2 to, BasePlayer hit)
method GetById (line 71) | public BasePlayer GetById(byte id)
method RemovePlayer (line 76) | public BasePlayer RemovePlayer(byte id)
method LogicUpdate (line 87) | public override void LogicUpdate()
method AddClientPlayer (line 93) | public void AddClientPlayer(ClientPlayer player, ClientPlayerView view)
method AddPlayer (line 99) | public void AddPlayer(RemotePlayer player, RemotePlayerView view)
method Clear (line 104) | public void Clear()
FILE: Assets/Code/Client/ClientPlayerView.cs
class ClientPlayerView (line 5) | public class ClientPlayerView : MonoBehaviour, IPlayerView
method Create (line 11) | public static ClientPlayerView Create(ClientPlayerView prefab, ClientP...
method Update (line 21) | private void Update()
method Destroy (line 40) | public void Destroy()
FILE: Assets/Code/Client/IPlayerView.cs
type IPlayerView (line 3) | public interface IPlayerView
method Destroy (line 5) | void Destroy();
FILE: Assets/Code/Client/RemotePlayer.cs
class RemotePlayer (line 6) | public class RemotePlayer : BasePlayer
method RemotePlayer (line 13) | public RemotePlayer(ClientPlayerManager manager, string name, PlayerJo...
method Spawn (line 21) | public override void Spawn(Vector2 position)
method UpdatePosition (line 27) | public void UpdatePosition(float delta)
method OnPlayerState (line 47) | public void OnPlayerState(PlayerState state)
FILE: Assets/Code/Client/RemotePlayerView.cs
class RemotePlayerView (line 5) | public class RemotePlayerView : MonoBehaviour, IPlayerView
method Create (line 9) | public static RemotePlayerView Create(RemotePlayerView prefab, RemoteP...
method Update (line 17) | private void Update()
method Destroy (line 24) | public void Destroy()
FILE: Assets/Code/Client/ShootEffect.cs
class ShootEffect (line 5) | public class ShootEffect : MonoBehaviour
method Init (line 17) | public void Init(Action<ShootEffect> onDeathCallback)
method Spawn (line 23) | public void Spawn(Vector2 from, Vector2 to)
method OnDeath (line 38) | private void OnDeath()
method Update (line 44) | private void Update()
FILE: Assets/Code/Client/UiController.cs
class UiController (line 8) | public class UiController : MonoBehaviour
method Awake (line 16) | private void Awake()
method OnHostClick (line 21) | public void OnHostClick()
method OnDisconnected (line 28) | private void OnDisconnected(DisconnectInfo info)
method OnConnectClick (line 34) | public void OnConnectClick()
FILE: Assets/Code/Server/AntilagSystem.cs
type StateInfo (line 6) | public struct StateInfo
class AntilagSystem (line 11) | public class AntilagSystem
method AntilagSystem (line 19) | public AntilagSystem(int maxTicks, int maxPlayers)
method GetStates (line 33) | private Dictionary<int, StateInfo> GetStates(ushort tick)
method StorePositions (line 40) | public void StorePositions(ushort serverTick, ServerPlayer[] players)
method TryApplyAntilag (line 60) | public bool TryApplyAntilag(ServerPlayer[] players, ushort tick, int e...
method RevertAntilag (line 92) | public void RevertAntilag(ServerPlayer[] players)
FILE: Assets/Code/Server/ServerLogic.cs
class ServerLogic (line 10) | public class ServerLogic : MonoBehaviour, INetEventListener
method StartServer (line 25) | public void StartServer()
method Awake (line 33) | private void Awake()
method OnDestroy (line 53) | private void OnDestroy()
method OnLogicUpdate (line 59) | private void OnLogicUpdate()
method Update (line 86) | private void Update()
method WriteSerializable (line 92) | private NetDataWriter WriteSerializable<T>(PacketType type, T packet) ...
method WritePacket (line 100) | private NetDataWriter WritePacket<T>(T packet) where T : class, new()
method OnJoinReceived (line 108) | private void OnJoinReceived(JoinPacket joinPacket, NetPeer peer)
method OnInputReceived (line 142) | private void OnInputReceived(NetPacketReader reader, NetPeer peer)
method SendShoot (line 155) | public void SendShoot(ref ShootPacket sp)
method OnPeerConnected (line 160) | void INetEventListener.OnPeerConnected(NetPeer peer)
method OnPeerDisconnected (line 165) | void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo...
method OnNetworkError (line 180) | void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError...
method OnNetworkReceive (line 185) | void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader ...
method OnNetworkReceiveUnconnected (line 205) | void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEn...
method OnNetworkLatencyUpdate (line 211) | void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency)
method OnConnectionRequest (line 220) | void INetEventListener.OnConnectionRequest(ConnectionRequest request)
FILE: Assets/Code/Server/ServerPlayer.cs
class ServerPlayer (line 7) | public class ServerPlayer : BasePlayer
method ServerPlayer (line 14) | public ServerPlayer(ServerPlayerManager playerManager, string name, Ne...
method ApplyInput (line 22) | public override void ApplyInput(PlayerInputPacket command, float delta)
method Update (line 30) | public override void Update(float delta)
FILE: Assets/Code/Server/ServerPlayerManager.cs
class ServerPlayerManager (line 8) | public class ServerPlayerManager : BasePlayerManager
method ServerPlayerManager (line 20) | public ServerPlayerManager(ServerLogic serverLogic)
method EnableAntilag (line 28) | public bool EnableAntilag(ServerPlayer forPlayer)
method DisableAntilag (line 33) | public void DisableAntilag()
method GetEnumerator (line 38) | public override IEnumerator<BasePlayer> GetEnumerator()
method OnShoot (line 48) | public override void OnShoot(BasePlayer from, Vector2 to, BasePlayer hit)
method AddPlayer (line 61) | public void AddPlayer(ServerPlayer player)
method LogicUpdate (line 76) | public override void LogicUpdate()
method RemovePlayer (line 86) | public bool RemovePlayer(byte playerId)
FILE: Assets/Code/Shared/BasePlayer.cs
class BasePlayer (line 5) | public abstract class BasePlayer
method BasePlayer (line 25) | protected BasePlayer(BasePlayerManager playerManager, string name, byt...
method Spawn (line 32) | public virtual void Spawn(Vector2 position)
method Shoot (line 39) | private void Shoot()
method ApplyInput (line 48) | public virtual void ApplyInput(PlayerInputPacket command, float delta)
method Update (line 76) | public virtual void Update(float delta)
FILE: Assets/Code/Shared/BasePlayerManager.cs
class BasePlayerManager (line 7) | public abstract class BasePlayerManager : IEnumerable<BasePlayer>
method GetEnumerator (line 9) | public abstract IEnumerator<BasePlayer> GetEnumerator();
method GetEnumerator (line 12) | IEnumerator IEnumerable.GetEnumerator()
method CastToPlayer (line 17) | public BasePlayer CastToPlayer(Vector2 from, Vector2 dir, float length...
method LogicUpdate (line 36) | public abstract void LogicUpdate();
method OnShoot (line 37) | public abstract void OnShoot(BasePlayer from, Vector2 to, BasePlayer h...
FILE: Assets/Code/Shared/Collisions.cs
class Collisions (line 3) | public static class Collisions
method CheckIntersection (line 5) | public static bool CheckIntersection(float x1, float y1, float x2, flo...
FILE: Assets/Code/Shared/Extensions.cs
class Extensions (line 6) | public static class Extensions
method Put (line 8) | public static void Put(this NetDataWriter writer, Vector2 vector)
method GetVector2 (line 14) | public static Vector2 GetVector2(this NetDataReader reader)
method GetRandomElement (line 22) | public static T GetRandomElement<T>(this T[] array)
FILE: Assets/Code/Shared/GamePackets.cs
type PacketType (line 7) | public enum PacketType : byte
class JoinPacket (line 17) | public class JoinPacket
class JoinAcceptPacket (line 22) | public class JoinAcceptPacket
class PlayerJoinedPacket (line 28) | public class PlayerJoinedPacket
class PlayerLeavedPacket (line 37) | public class PlayerLeavedPacket
type SpawnPacket (line 43) | public struct SpawnPacket : INetSerializable
method Serialize (line 48) | public void Serialize(NetDataWriter writer)
method Deserialize (line 54) | public void Deserialize(NetDataReader reader)
type MovementKeys (line 61) | [Flags]
type ShootPacket (line 71) | public struct ShootPacket : INetSerializable
method Serialize (line 78) | public void Serialize(NetDataWriter writer)
method Deserialize (line 86) | public void Deserialize(NetDataReader reader)
type PlayerInputPacket (line 95) | public struct PlayerInputPacket : INetSerializable
method Serialize (line 102) | public void Serialize(NetDataWriter writer)
method Deserialize (line 110) | public void Deserialize(NetDataReader reader)
type PlayerState (line 119) | public struct PlayerState : INetSerializable
method Serialize (line 128) | public void Serialize(NetDataWriter writer)
method Deserialize (line 136) | public void Deserialize(NetDataReader reader)
type ServerState (line 145) | public struct ServerState : INetSerializable
method Serialize (line 157) | public void Serialize(NetDataWriter writer)
method Deserialize (line 166) | public void Deserialize(NetDataReader reader)
FILE: Assets/Code/Shared/GamePool.cs
class GamePool (line 5) | public class GamePool<T> where T : class
method GamePool (line 11) | public GamePool(Func<T> creator) : this(creator, 8)
method GamePool (line 16) | public GamePool(Func<T> creator, int capacity)
method Get (line 22) | public T Get()
method Put (line 34) | public void Put(T gameObject)
FILE: Assets/Code/Shared/GameTimer.cs
type GameTimer (line 5) | public struct GameTimer
method GameTimer (line 20) | public GameTimer(float maxTime)
method Reset (line 26) | public void Reset()
method UpdateAsCooldown (line 31) | public void UpdateAsCooldown(float delta)
method Update (line 36) | public void Update(float delta, Action onUpdate)
FILE: Assets/Code/Shared/LiteRingBuffer.cs
class LiteRingBuffer (line 7) | public class LiteRingBuffer<T> : IEnumerable<T>
method LiteRingBuffer (line 17) | public LiteRingBuffer(int count)
method Add (line 23) | public void Add(T element)
method FastClear (line 32) | public void FastClear()
method RemoveFromStart (line 44) | public void RemoveFromStart(int count)
method GetEnumerator (line 52) | public IEnumerator<T> GetEnumerator()
method GetEnumerator (line 62) | IEnumerator IEnumerable.GetEnumerator()
FILE: Assets/Code/Shared/LogicTimer.cs
class LogicTimer (line 6) | public class LogicTimer
method LogicTimer (line 19) | public LogicTimer(Action action)
method Start (line 25) | public void Start()
method Stop (line 32) | public void Stop()
method Update (line 37) | public void Update()
FILE: Assets/Code/Shared/NetworkGeneral.cs
class NetworkGeneral (line 5) | public static class NetworkGeneral
method SeqDiff (line 13) | public static int SeqDiff(int a, int b)
method Diff (line 17) | public static int Diff(int a, int b, int halfMax)
FILE: Assets/Plugins/LiteNetLib/BaseChannel.cs
class BaseChannel (line 5) | internal abstract class BaseChannel
method BaseChannel (line 11) | protected BaseChannel(NetPeer peer)
method AddToQueue (line 22) | public void AddToQueue(NetPacket packet)
method SendNextPackets (line 28) | public abstract void SendNextPackets();
method ProcessPacket (line 29) | public abstract bool ProcessPacket(NetPacket packet);
FILE: Assets/Plugins/LiteNetLib/ConnectionRequest.cs
type ConnectionRequestResult (line 7) | internal enum ConnectionRequestResult
class ConnectionRequest (line 15) | public class ConnectionRequest
method TryActivate (line 27) | private bool TryActivate()
method UpdateRequest (line 32) | internal void UpdateRequest(NetConnectRequestPacket connRequest)
method ConnectionRequest (line 41) | internal ConnectionRequest(
method AcceptIfKey (line 55) | public NetPeer AcceptIfKey(string key)
method Accept (line 80) | public NetPeer Accept()
method Reject (line 88) | public void Reject(byte[] rejectData, int start, int length, bool force)
method Reject (line 96) | public void Reject(byte[] rejectData, int start, int length)
method RejectForce (line 102) | public void RejectForce(byte[] rejectData, int start, int length)
method RejectForce (line 107) | public void RejectForce()
method RejectForce (line 112) | public void RejectForce(byte[] rejectData)
method RejectForce (line 117) | public void RejectForce(NetDataWriter rejectData)
method Reject (line 122) | public void Reject()
method Reject (line 127) | public void Reject(byte[] rejectData)
method Reject (line 132) | public void Reject(NetDataWriter rejectData)
FILE: Assets/Plugins/LiteNetLib/INetEventListener.cs
type UnconnectedMessageType (line 9) | public enum UnconnectedMessageType
type DisconnectReason (line 18) | public enum DisconnectReason
type DisconnectInfo (line 36) | public struct DisconnectInfo
type INetEventListener (line 54) | public interface INetEventListener
method OnPeerConnected (line 60) | void OnPeerConnected(NetPeer peer);
method OnPeerDisconnected (line 67) | void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo);
method OnNetworkError (line 74) | void OnNetworkError(IPEndPoint endPoint, SocketError socketError);
method OnNetworkReceive (line 82) | void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMe...
method OnNetworkReceiveUnconnected (line 90) | void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketR...
method OnNetworkLatencyUpdate (line 97) | void OnNetworkLatencyUpdate(NetPeer peer, int latency);
method OnConnectionRequest (line 103) | void OnConnectionRequest(ConnectionRequest request);
type IDeliveryEventListener (line 106) | public interface IDeliveryEventListener
method OnMessageDelivered (line 113) | void OnMessageDelivered(NetPeer peer, object userData);
class EventBasedNetListener (line 116) | public class EventBasedNetListener : INetEventListener, IDeliveryEventLi...
method ClearPeerConnectedEvent (line 136) | public void ClearPeerConnectedEvent()
method ClearPeerDisconnectedEvent (line 141) | public void ClearPeerDisconnectedEvent()
method ClearNetworkErrorEvent (line 146) | public void ClearNetworkErrorEvent()
method ClearNetworkReceiveEvent (line 151) | public void ClearNetworkReceiveEvent()
method ClearNetworkReceiveUnconnectedEvent (line 156) | public void ClearNetworkReceiveUnconnectedEvent()
method ClearNetworkLatencyUpdateEvent (line 161) | public void ClearNetworkLatencyUpdateEvent()
method ClearConnectionRequestEvent (line 166) | public void ClearConnectionRequestEvent()
method ClearDeliveryEvent (line 171) | public void ClearDeliveryEvent()
method OnPeerConnected (line 176) | void INetEventListener.OnPeerConnected(NetPeer peer)
method OnPeerDisconnected (line 182) | void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo...
method OnNetworkError (line 188) | void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError...
method OnNetworkReceive (line 194) | void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader ...
method OnNetworkReceiveUnconnected (line 200) | void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEn...
method OnNetworkLatencyUpdate (line 206) | void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency)
method OnConnectionRequest (line 212) | void INetEventListener.OnConnectionRequest(ConnectionRequest request)
method OnMessageDelivered (line 218) | void IDeliveryEventListener.OnMessageDelivered(NetPeer peer, object us...
FILE: Assets/Plugins/LiteNetLib/Layers/Crc32cLayer.cs
class Crc32cLayer (line 7) | public sealed class Crc32cLayer : PacketLayerBase
method Crc32cLayer (line 9) | public Crc32cLayer() : base(CRC32C.ChecksumSize)
method ProcessInboundPacket (line 14) | public override void ProcessInboundPacket(IPEndPoint endPoint, ref byt...
method ProcessOutBoundPacket (line 31) | public override void ProcessOutBoundPacket(IPEndPoint endPoint, ref by...
FILE: Assets/Plugins/LiteNetLib/Layers/PacketLayerBase.cs
class PacketLayerBase (line 5) | public abstract class PacketLayerBase
method PacketLayerBase (line 9) | protected PacketLayerBase(int extraPacketSizeForLayer)
method ProcessInboundPacket (line 14) | public abstract void ProcessInboundPacket(IPEndPoint endPoint, ref byt...
method ProcessOutBoundPacket (line 15) | public abstract void ProcessOutBoundPacket(IPEndPoint endPoint, ref by...
FILE: Assets/Plugins/LiteNetLib/Layers/XorEncryptLayer.cs
class XorEncryptLayer (line 7) | public class XorEncryptLayer : PacketLayerBase
method XorEncryptLayer (line 11) | public XorEncryptLayer() : base(0)
method XorEncryptLayer (line 16) | public XorEncryptLayer(byte[] key) : this()
method XorEncryptLayer (line 21) | public XorEncryptLayer(string key) : this()
method SetKey (line 26) | public void SetKey(string key)
method SetKey (line 31) | public void SetKey(byte[] key)
method ProcessInboundPacket (line 38) | public override void ProcessInboundPacket(IPEndPoint endPoint, ref byt...
method ProcessOutBoundPacket (line 49) | public override void ProcessOutBoundPacket(IPEndPoint endPoint, ref by...
FILE: Assets/Plugins/LiteNetLib/NatPunchModule.cs
type NatAddressType (line 8) | public enum NatAddressType
type INatPunchListener (line 14) | public interface INatPunchListener
method OnNatIntroductionRequest (line 16) | void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint rem...
method OnNatIntroductionSuccess (line 17) | void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressTyp...
class EventBasedNatPunchListener (line 20) | public class EventBasedNatPunchListener : INatPunchListener
method OnNatIntroductionRequest (line 28) | void INatPunchListener.OnNatIntroductionRequest(IPEndPoint localEndPoi...
method OnNatIntroductionSuccess (line 34) | void INatPunchListener.OnNatIntroductionSuccess(IPEndPoint targetEndPo...
class NatPunchModule (line 44) | public sealed class NatPunchModule
type RequestEventData (line 46) | struct RequestEventData
type SuccessEventData (line 53) | struct SuccessEventData
class NatIntroduceRequestPacket (line 60) | class NatIntroduceRequestPacket
class NatIntroduceResponsePacket (line 66) | class NatIntroduceResponsePacket
class NatPunchPacket (line 73) | class NatPunchPacket
method NatPunchModule (line 88) | internal NatPunchModule(NetSocket socket)
method ProcessMessage (line 96) | internal void ProcessMessage(IPEndPoint senderEndPoint, NetPacket packet)
method Init (line 105) | public void Init(INatPunchListener listener)
method Send (line 110) | private void Send<T>(T packet, IPEndPoint target) where T : class, new()
method NatIntroduce (line 119) | public void NatIntroduce(
method PollEvents (line 142) | public void PollEvents()
method SendNatIntroduceRequest (line 167) | public void SendNatIntroduceRequest(string host, int port, string addi...
method SendNatIntroduceRequest (line 172) | public void SendNatIntroduceRequest(IPEndPoint masterServerEndPoint, s...
method OnNatIntroductionRequest (line 191) | private void OnNatIntroductionRequest(NatIntroduceRequestPacket req, I...
method OnNatIntroductionResponse (line 205) | private void OnNatIntroductionResponse(NatIntroduceResponsePacket req)
method OnNatPunch (line 227) | private void OnNatPunch(NatPunchPacket req, IPEndPoint senderEndPoint)
FILE: Assets/Plugins/LiteNetLib/NetConstants.cs
type DeliveryMethod (line 6) | public enum DeliveryMethod : byte
class NetConstants (line 37) | public static class NetConstants
FILE: Assets/Plugins/LiteNetLib/NetDebug.cs
class InvalidPacketException (line 6) | public class InvalidPacketException : ArgumentException
method InvalidPacketException (line 8) | public InvalidPacketException(string message) : base(message)
class TooBigPacketException (line 13) | public class TooBigPacketException : InvalidPacketException
method TooBigPacketException (line 15) | public TooBigPacketException(string message) : base(message)
type NetLogLevel (line 20) | public enum NetLogLevel
type INetLogger (line 31) | public interface INetLogger
method WriteNet (line 33) | void WriteNet(NetLogLevel level, string str, params object[] args);
class NetDebug (line 40) | public static class NetDebug
method WriteLogic (line 44) | private static void WriteLogic(NetLogLevel logLevel, string str, param...
method Write (line 63) | [Conditional("DEBUG_MESSAGES")]
method Write (line 69) | [Conditional("DEBUG_MESSAGES")]
method WriteForce (line 75) | [Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")]
method WriteForce (line 81) | [Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")]
method WriteError (line 87) | internal static void WriteError(string str, params object[] args)
FILE: Assets/Plugins/LiteNetLib/NetManager.cs
type IPv6Mode (line 13) | public enum IPv6Mode
class NetPacketReader (line 20) | public sealed class NetPacketReader : NetDataReader
method NetPacketReader (line 26) | internal NetPacketReader(NetManager manager, NetEvent evt)
method SetSource (line 32) | internal void SetSource(NetPacket packet, int headerSize)
method RecycleInternal (line 40) | internal void RecycleInternal()
method Recycle (line 49) | public void Recycle()
class NetEvent (line 57) | internal sealed class NetEvent
type EType (line 61) | public enum EType
method NetEvent (line 85) | public NetEvent(NetManager manager)
class NetManager (line 94) | public class NetManager : INetSocketListener, IEnumerable<NetPeer>
class IPEndPointComparer (line 96) | private class IPEndPointComparer : IEqualityComparer<IPEndPoint>
method Equals (line 98) | public bool Equals(IPEndPoint x, IPEndPoint y)
method GetHashCode (line 103) | public int GetHashCode(IPEndPoint obj)
type NetPeerEnumerator (line 109) | public struct NetPeerEnumerator : IEnumerator<NetPeer>
method NetPeerEnumerator (line 114) | public NetPeerEnumerator(NetPeer p)
method Dispose (line 120) | public void Dispose()
method MoveNext (line 125) | public bool MoveNext()
method Reset (line 131) | public void Reset()
type IncomingData (line 148) | private struct IncomingData
method GetPeerById (line 343) | public NetPeer GetPeerById(int id)
method TryGetPeer (line 358) | private bool TryGetPeer(IPEndPoint endPoint, out NetPeer peer)
method AddPeer (line 366) | private void AddPeer(NetPeer peer)
method RemovePeer (line 387) | private void RemovePeer(NetPeer peer)
method RemovePeerInternal (line 394) | private void RemovePeerInternal(NetPeer peer)
method NetManager (line 417) | public NetManager(INetEventListener listener, PacketLayerBase extraPac...
method ConnectionLatencyUpdated (line 435) | internal void ConnectionLatencyUpdated(NetPeer fromPeer, int latency)
method MessageDelivered (line 440) | internal void MessageDelivered(NetPeer fromPeer, object userData)
method SendRawAndRecycle (line 446) | internal int SendRawAndRecycle(NetPacket packet, IPEndPoint remoteEndP...
method SendRaw (line 453) | internal int SendRaw(NetPacket packet, IPEndPoint remoteEndPoint)
method SendRaw (line 458) | internal int SendRaw(byte[] message, int start, int length, IPEndPoint...
method DisconnectPeerForce (line 508) | internal void DisconnectPeerForce(NetPeer peer,
method DisconnectPeer (line 516) | private void DisconnectPeer(
method CreateEvent (line 540) | private void CreateEvent(
method ProcessEvent (line 592) | private void ProcessEvent(NetEvent evt)
method RecycleEvent (line 639) | internal void RecycleEvent(NetEvent evt)
method UpdateLogic (line 652) | private void UpdateLogic()
method OnMessageReceived (line 712) | void INetSocketListener.OnMessageReceived(byte[] data, int length, Soc...
method OnConnectionSolved (line 760) | internal NetPeer OnConnectionSolved(ConnectionRequest request, byte[] ...
method GetNextPeerId (line 812) | private int GetNextPeerId()
method ProcessConnectRequest (line 818) | private void ProcessConnectRequest(
method DataReceived (line 886) | private void DataReceived(byte[] reusableBuffer, int count, IPEndPoint...
method CreateReceiveEvent (line 1026) | internal void CreateReceiveEvent(NetPacket packet, DeliveryMethod meth...
method SendToAll (line 1058) | public void SendToAll(NetDataWriter writer, DeliveryMethod options)
method SendToAll (line 1068) | public void SendToAll(byte[] data, DeliveryMethod options)
method SendToAll (line 1080) | public void SendToAll(byte[] data, int start, int length, DeliveryMeth...
method SendToAll (line 1091) | public void SendToAll(NetDataWriter writer, byte channelNumber, Delive...
method SendToAll (line 1102) | public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod ...
method SendToAll (line 1115) | public void SendToAll(byte[] data, int start, int length, byte channel...
method SendToAll (line 1135) | public void SendToAll(NetDataWriter writer, DeliveryMethod options, Ne...
method SendToAll (line 1146) | public void SendToAll(byte[] data, DeliveryMethod options, NetPeer exc...
method SendToAll (line 1159) | public void SendToAll(byte[] data, int start, int length, DeliveryMeth...
method SendToAll (line 1171) | public void SendToAll(NetDataWriter writer, byte channelNumber, Delive...
method SendToAll (line 1183) | public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod ...
method SendToAll (line 1198) | public void SendToAll(byte[] data, int start, int length, byte channel...
method Start (line 1218) | public bool Start()
method Start (line 1229) | public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port)
method Start (line 1244) | public bool Start(string addressIPv4, string addressIPv6, int port)
method Start (line 1255) | public bool Start(int port)
method SendUnconnectedMessage (line 1266) | public bool SendUnconnectedMessage(byte[] message, IPEndPoint remoteEn...
method SendUnconnectedMessage (line 1277) | public bool SendUnconnectedMessage(NetDataWriter writer, IPEndPoint re...
method SendUnconnectedMessage (line 1290) | public bool SendUnconnectedMessage(byte[] message, int start, int leng...
method SendBroadcast (line 1297) | public bool SendBroadcast(NetDataWriter writer, int port)
method SendBroadcast (line 1302) | public bool SendBroadcast(byte[] data, int port)
method SendBroadcast (line 1307) | public bool SendBroadcast(byte[] data, int start, int length, int port)
method TriggerUpdate (line 1333) | public void TriggerUpdate()
method PollEvents (line 1341) | public void PollEvents()
method Connect (line 1365) | public NetPeer Connect(string address, int port, string key)
method Connect (line 1378) | public NetPeer Connect(string address, int port, NetDataWriter connect...
method Connect (line 1400) | public NetPeer Connect(IPEndPoint target, string key)
method Connect (line 1412) | public NetPeer Connect(IPEndPoint target, NetDataWriter connectionData)
method Stop (line 1454) | public void Stop()
method Stop (line 1463) | public void Stop(bool sendDisconnectMessages)
method GetPeersCount (line 1501) | public int GetPeersCount(ConnectionState peerState)
method GetPeersNonAlloc (line 1519) | public void GetPeersNonAlloc(List<NetPeer> peers, ConnectionState peer...
method DisconnectAll (line 1534) | public void DisconnectAll()
method DisconnectAll (line 1545) | public void DisconnectAll(byte[] data, int start, int count)
method DisconnectPeerForce (line 1568) | public void DisconnectPeerForce(NetPeer peer)
method DisconnectPeer (line 1577) | public void DisconnectPeer(NetPeer peer)
method DisconnectPeer (line 1587) | public void DisconnectPeer(NetPeer peer, byte[] data)
method DisconnectPeer (line 1597) | public void DisconnectPeer(NetPeer peer, NetDataWriter writer)
method DisconnectPeer (line 1609) | public void DisconnectPeer(NetPeer peer, byte[] data, int start, int c...
method GetEnumerator (line 1622) | public NetPeerEnumerator GetEnumerator()
method GetEnumerator (line 1627) | IEnumerator<NetPeer> IEnumerable<NetPeer>.GetEnumerator()
method GetEnumerator (line 1632) | IEnumerator IEnumerable.GetEnumerator()
FILE: Assets/Plugins/LiteNetLib/NetPacket.cs
type PacketProperty (line 7) | internal enum PacketProperty : byte
class NetPacket (line 29) | internal sealed class NetPacket
method NetPacket (line 34) | static NetPacket()
method MarkFragmented (line 91) | public void MarkFragmented()
method NetPacket (line 130) | public NetPacket(int size)
method NetPacket (line 136) | public NetPacket(PacketProperty property, int size)
method GetHeaderSize (line 144) | public static int GetHeaderSize(PacketProperty property)
method GetHeaderSize (line 149) | public int GetHeaderSize()
method FromBytes (line 155) | public bool FromBytes(byte[] data, int start, int packetSize)
class NetConnectRequestPacket (line 175) | internal sealed class NetConnectRequestPacket
method NetConnectRequestPacket (line 183) | private NetConnectRequestPacket(long connectionTime, byte connectionNu...
method GetProtocolId (line 191) | public static int GetProtocolId(NetPacket packet)
method FromData (line 196) | public static NetConnectRequestPacket FromData(NetPacket packet)
method Make (line 219) | public static NetPacket Make(NetDataWriter connectData, SocketAddress ...
class NetConnectAcceptPacket (line 235) | internal sealed class NetConnectAcceptPacket
method NetConnectAcceptPacket (line 242) | private NetConnectAcceptPacket(long connectionId, byte connectionNumbe...
method FromData (line 249) | public static NetConnectAcceptPacket FromData(NetPacket packet)
method Make (line 267) | public static NetPacket Make(long connectId, byte connectNum, bool reu...
FILE: Assets/Plugins/LiteNetLib/NetPacketPool.cs
class NetPacketPool (line 6) | internal sealed class NetPacketPool
method GetWithData (line 11) | public NetPacket GetWithData(PacketProperty property, byte[] data, int...
method GetWithProperty (line 21) | public NetPacket GetWithProperty(PacketProperty property, int size)
method GetWithProperty (line 28) | public NetPacket GetWithProperty(PacketProperty property)
method GetPacket (line 35) | public NetPacket GetPacket(int size)
method Recycle (line 55) | public void Recycle(NetPacket packet)
FILE: Assets/Plugins/LiteNetLib/NetPeer.cs
type ConnectionState (line 16) | [Flags]
type ConnectRequestResult (line 26) | internal enum ConnectRequestResult
type DisconnectResult (line 34) | internal enum DisconnectResult
type ShutdownResult (line 41) | internal enum ShutdownResult
class NetPeer (line 51) | public class NetPeer
class IncomingFragments (line 99) | private class IncomingFragments
method NetPeer (line 199) | internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int...
method SetMtu (line 221) | private void SetMtu(int mtuIdx)
method GetPacketsCountInReliableQueue (line 232) | public int GetPacketsCountInReliableQueue(byte channelNumber, bool ord...
method CreateChannel (line 240) | private BaseChannel CreateChannel(byte idx)
method NetPeer (line 276) | internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int...
method NetPeer (line 294) | internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int...
method Reject (line 310) | internal void Reject(long connectionId, byte connectionNumber, byte[] ...
method ProcessConnectAccept (line 317) | internal bool ProcessConnectAccept(NetConnectAcceptPacket packet)
method GetMaxSinglePacketSize (line 342) | public int GetMaxSinglePacketSize(DeliveryMethod options)
method SendWithDeliveryEvent (line 357) | public void SendWithDeliveryEvent(byte[] data, byte channelNumber, Del...
method SendWithDeliveryEvent (line 376) | public void SendWithDeliveryEvent(byte[] data, int start, int length, ...
method SendWithDeliveryEvent (line 393) | public void SendWithDeliveryEvent(NetDataWriter dataWriter, byte chann...
method Send (line 410) | public void Send(byte[] data, DeliveryMethod deliveryMethod)
method Send (line 425) | public void Send(NetDataWriter dataWriter, DeliveryMethod deliveryMethod)
method Send (line 442) | public void Send(byte[] data, int start, int length, DeliveryMethod op...
method Send (line 458) | public void Send(byte[] data, byte channelNumber, DeliveryMethod deliv...
method Send (line 474) | public void Send(NetDataWriter dataWriter, byte channelNumber, Deliver...
method Send (line 492) | public void Send(byte[] data, int start, int length, byte channelNumbe...
method SendInternal (line 497) | private void SendInternal(
method Disconnect (line 589) | public void Disconnect(byte[] data)
method Disconnect (line 594) | public void Disconnect(NetDataWriter writer)
method Disconnect (line 599) | public void Disconnect(byte[] data, int start, int count)
method Disconnect (line 604) | public void Disconnect()
method ProcessDisconnect (line 609) | internal DisconnectResult ProcessDisconnect(NetPacket packet)
method Shutdown (line 623) | internal ShutdownResult Shutdown(byte[] data, int start, int length, b...
method UpdateRoundTripTime (line 667) | private void UpdateRoundTripTime(int roundTripTime)
method AddReliablePacket (line 675) | internal void AddReliablePacket(DeliveryMethod method, NetPacket p)
method ProcessMtuPacket (line 750) | private void ProcessMtuPacket(NetPacket packet)
method UpdateMtuLogic (line 791) | private void UpdateMtuLogic(int deltaTime)
method ProcessConnectRequest (line 826) | internal ConnectRequestResult ProcessConnectRequest(NetConnectRequestP...
method ProcessPacket (line 878) | internal void ProcessPacket(NetPacket packet)
method SendMerged (line 977) | private void SendMerged()
method SendUserData (line 1003) | internal void SendUserData(NetPacket packet)
method Update (line 1031) | internal void Update(int deltaTime)
method RecycleAndDeliver (line 1135) | internal void RecycleAndDeliver(NetPacket packet)
FILE: Assets/Plugins/LiteNetLib/NetSocket.cs
class UnitySocketFix (line 19) | public class UnitySocketFix : MonoBehaviour
method Update (line 29) | private void Update()
method OnApplicationPause (line 35) | private void OnApplicationPause(bool pause)
type INetSocketListener (line 56) | internal interface INetSocketListener
method OnMessageReceived (line 58) | void OnMessageReceived(byte[] data, int length, SocketError errorCode,...
class NetSocket (line 61) | internal sealed class NetSocket
method OnErrorRestore (line 75) | public void OnErrorRestore()
method NetSocket (line 107) | static NetSocket()
method NetSocket (line 125) | public NetSocket(INetSocketListener listener)
method IsActive (line 130) | private bool IsActive()
method ReceiveLogic (line 140) | private void ReceiveLogic(object state)
method Bind (line 193) | public bool Bind(IPAddress addressIPv4, IPAddress addressIPv6, int port,...
method BindSocket (line 257) | private bool BindSocket(Socket socket, IPEndPoint ep, bool reuseAddress,...
FILE: Assets/Plugins/LiteNetLib/NetStatistics.cs
class NetStatistics (line 5) | public sealed class NetStatistics
method Reset (line 46) | public void Reset()
method IncrementPacketsSent (line 55) | public void IncrementPacketsSent()
method IncrementPacketsReceived (line 60) | public void IncrementPacketsReceived()
method AddBytesSent (line 65) | public void AddBytesSent(long bytesSent)
method AddBytesReceived (line 70) | public void AddBytesReceived(long bytesReceived)
method IncrementPacketLoss (line 75) | public void IncrementPacketLoss()
method AddPacketLoss (line 80) | public void AddPacketLoss(long packetLoss)
method ToString (line 85) | public override string ToString()
FILE: Assets/Plugins/LiteNetLib/NetUtils.cs
type LocalAddrType (line 12) | [Flags]
class NetUtils (line 23) | public static class NetUtils
method MakeEndPoint (line 25) | public static IPEndPoint MakeEndPoint(string hostStr, int port)
method ResolveAddress (line 30) | public static IPAddress ResolveAddress(string hostStr)
method ResolveAddress (line 49) | private static IPAddress ResolveAddress(string hostStr, AddressFamily ...
method ResolveAddresses (line 62) | private static IPAddress[] ResolveAddresses(string hostStr)
method GetLocalIpList (line 79) | public static List<string> GetLocalIpList(LocalAddrType addrType)
method GetLocalIpList (line 91) | public static void GetLocalIpList(IList<string> targetList, LocalAddrT...
method GetLocalIp (line 150) | public static string GetLocalIp(LocalAddrType addrType)
method PrintInterfaceInfos (line 163) | internal static void PrintInterfaceInfos()
method RelativeSequenceNumber (line 192) | internal static int RelativeSequenceNumber(int number, int expected)
FILE: Assets/Plugins/LiteNetLib/ReliableChannel.cs
class ReliableChannel (line 5) | internal sealed class ReliableChannel : BaseChannel
type PendingPacket (line 7) | private struct PendingPacket
method ToString (line 13) | public override string ToString()
method Init (line 18) | public void Init(NetPacket packet)
method TrySend (line 24) | public void TrySend(long currentTime, NetPeer peer)
method Clear (line 41) | public bool Clear(NetPeer peer)
method ReliableChannel (line 71) | public ReliableChannel(NetPeer peer, bool ordered, byte id) : base(peer)
method ProcessAck (line 99) | private void ProcessAck(NetPacket packet)
method SendNextPackets (line 165) | public override void SendNextPackets()
method ProcessPacket (line 201) | public override bool ProcessPacket(NetPacket packet)
FILE: Assets/Plugins/LiteNetLib/SequencedChannel.cs
class SequencedChannel (line 5) | internal sealed class SequencedChannel : BaseChannel
method SequencedChannel (line 16) | public SequencedChannel(NetPeer peer, bool reliable, byte id) : base(p...
method SendNextPackets (line 24) | public override void SendNextPackets()
method ProcessPacket (line 72) | public override bool ProcessPacket(NetPacket packet)
FILE: Assets/Plugins/LiteNetLib/Utils/CRC32C.cs
class CRC32C (line 10) | public static class CRC32C
method CRC32C (line 16) | static CRC32C()
method Compute (line 42) | public static uint Compute(byte[] input, int offset, int length)
FILE: Assets/Plugins/LiteNetLib/Utils/FastBitConverter.cs
class FastBitConverter (line 5) | public static class FastBitConverter
type ConverterHelperDouble (line 7) | [StructLayout(LayoutKind.Explicit)]
type ConverterHelperFloat (line 17) | [StructLayout(LayoutKind.Explicit)]
method WriteLittleEndian (line 27) | private static void WriteLittleEndian(byte[] buffer, int offset, ulong...
method WriteLittleEndian (line 50) | private static void WriteLittleEndian(byte[] buffer, int offset, int d...
method WriteLittleEndian (line 65) | public static void WriteLittleEndian(byte[] buffer, int offset, short ...
method GetBytes (line 76) | public static void GetBytes(byte[] bytes, int startIndex, double value)
method GetBytes (line 82) | public static void GetBytes(byte[] bytes, int startIndex, float value)
method GetBytes (line 88) | public static void GetBytes(byte[] bytes, int startIndex, short value)
method GetBytes (line 93) | public static void GetBytes(byte[] bytes, int startIndex, ushort value)
method GetBytes (line 98) | public static void GetBytes(byte[] bytes, int startIndex, int value)
method GetBytes (line 103) | public static void GetBytes(byte[] bytes, int startIndex, uint value)
method GetBytes (line 108) | public static void GetBytes(byte[] bytes, int startIndex, long value)
method GetBytes (line 113) | public static void GetBytes(byte[] bytes, int startIndex, ulong value)
FILE: Assets/Plugins/LiteNetLib/Utils/INetSerializable.cs
type INetSerializable (line 3) | public interface INetSerializable
method Serialize (line 5) | void Serialize(NetDataWriter writer);
method Deserialize (line 6) | void Deserialize(NetDataReader reader);
FILE: Assets/Plugins/LiteNetLib/Utils/NetDataReader.cs
class NetDataReader (line 7) | public class NetDataReader
method SkipBytes (line 54) | public void SkipBytes(int count)
method SetSource (line 59) | public void SetSource(NetDataWriter dataWriter)
method SetSource (line 67) | public void SetSource(byte[] source)
method SetSource (line 75) | public void SetSource(byte[] source, int offset)
method SetSource (line 83) | public void SetSource(byte[] source, int offset, int maxSize)
method NetDataReader (line 91) | public NetDataReader()
method NetDataReader (line 96) | public NetDataReader(NetDataWriter writer)
method NetDataReader (line 101) | public NetDataReader(byte[] source)
method NetDataReader (line 106) | public NetDataReader(byte[] source, int offset)
method NetDataReader (line 111) | public NetDataReader(byte[] source, int offset, int maxSize)
method GetNetEndPoint (line 117) | public IPEndPoint GetNetEndPoint()
method GetByte (line 124) | public byte GetByte()
method GetSByte (line 131) | public sbyte GetSByte()
method GetBoolArray (line 138) | public bool[] GetBoolArray()
method GetUShortArray (line 148) | public ushort[] GetUShortArray()
method GetShortArray (line 158) | public short[] GetShortArray()
method GetLongArray (line 168) | public long[] GetLongArray()
method GetULongArray (line 178) | public ulong[] GetULongArray()
method GetIntArray (line 188) | public int[] GetIntArray()
method GetUIntArray (line 198) | public uint[] GetUIntArray()
method GetFloatArray (line 208) | public float[] GetFloatArray()
method GetDoubleArray (line 218) | public double[] GetDoubleArray()
method GetStringArray (line 228) | public string[] GetStringArray()
method GetStringArray (line 240) | public string[] GetStringArray(int maxStringLength)
method GetBool (line 252) | public bool GetBool()
method GetChar (line 259) | public char GetChar()
method GetUShort (line 266) | public ushort GetUShort()
method GetShort (line 273) | public short GetShort()
method GetLong (line 280) | public long GetLong()
method GetULong (line 287) | public ulong GetULong()
method GetInt (line 294) | public int GetInt()
method GetUInt (line 301) | public uint GetUInt()
method GetFloat (line 308) | public float GetFloat()
method GetDouble (line 315) | public double GetDouble()
method GetString (line 322) | public string GetString(int maxLength)
method GetString (line 341) | public string GetString()
method GetRemainingBytesSegment (line 354) | public ArraySegment<byte> GetRemainingBytesSegment()
method Get (line 361) | public T Get<T>() where T : INetSerializable, new()
method GetRemainingBytes (line 368) | public byte[] GetRemainingBytes()
method GetBytes (line 376) | public void GetBytes(byte[] destination, int start, int count)
method GetBytes (line 382) | public void GetBytes(byte[] destination, int count)
method GetSBytesWithLength (line 388) | public sbyte[] GetSBytesWithLength()
method GetBytesWithLength (line 397) | public byte[] GetBytesWithLength()
method PeekByte (line 409) | public byte PeekByte()
method PeekSByte (line 414) | public sbyte PeekSByte()
method PeekBool (line 419) | public bool PeekBool()
method PeekChar (line 424) | public char PeekChar()
method PeekUShort (line 429) | public ushort PeekUShort()
method PeekShort (line 434) | public short PeekShort()
method PeekLong (line 439) | public long PeekLong()
method PeekULong (line 444) | public ulong PeekULong()
method PeekInt (line 449) | public int PeekInt()
method PeekUInt (line 454) | public uint PeekUInt()
method PeekFloat (line 459) | public float PeekFloat()
method PeekDouble (line 464) | public double PeekDouble()
method PeekString (line 469) | public string PeekString(int maxLength)
method PeekString (line 487) | public string PeekString()
method TryGetByte (line 501) | public bool TryGetByte(out byte result)
method TryGetSByte (line 512) | public bool TryGetSByte(out sbyte result)
method TryGetBool (line 523) | public bool TryGetBool(out bool result)
method TryGetChar (line 534) | public bool TryGetChar(out char result)
method TryGetShort (line 545) | public bool TryGetShort(out short result)
method TryGetUShort (line 556) | public bool TryGetUShort(out ushort result)
method TryGetInt (line 567) | public bool TryGetInt(out int result)
method TryGetUInt (line 578) | public bool TryGetUInt(out uint result)
method TryGetLong (line 589) | public bool TryGetLong(out long result)
method TryGetULong (line 600) | public bool TryGetULong(out ulong result)
method TryGetFloat (line 611) | public bool TryGetFloat(out float result)
method TryGetDouble (line 622) | public bool TryGetDouble(out double result)
method TryGetString (line 633) | public bool TryGetString(out string result)
method TryGetStringArray (line 648) | public bool TryGetStringArray(out string[] result)
method TryGetBytesWithLength (line 670) | public bool TryGetBytesWithLength(out byte[] result)
method Clear (line 686) | public void Clear()
FILE: Assets/Plugins/LiteNetLib/Utils/NetDataWriter.cs
class NetDataWriter (line 7) | public class NetDataWriter
method NetDataWriter (line 19) | public NetDataWriter() : this(true, InitialSize)
method NetDataWriter (line 23) | public NetDataWriter(bool autoResize) : this(autoResize, InitialSize)
method NetDataWriter (line 27) | public NetDataWriter(bool autoResize, int initialSize)
method FromBytes (line 38) | public static NetDataWriter FromBytes(byte[] bytes, bool copy)
method FromBytes (line 55) | public static NetDataWriter FromBytes(byte[] bytes, int offset, int le...
method FromString (line 62) | public static NetDataWriter FromString(string value)
method ResizeIfNeed (line 69) | public void ResizeIfNeed(int newSize)
method Reset (line 80) | public void Reset(int size)
method Reset (line 86) | public void Reset()
method CopyData (line 91) | public byte[] CopyData()
method Put (line 108) | public void Put(float value)
method Put (line 116) | public void Put(double value)
method Put (line 124) | public void Put(long value)
method Put (line 132) | public void Put(ulong value)
method Put (line 140) | public void Put(int value)
method Put (line 148) | public void Put(uint value)
method Put (line 156) | public void Put(char value)
method Put (line 164) | public void Put(ushort value)
method Put (line 172) | public void Put(short value)
method Put (line 180) | public void Put(sbyte value)
method Put (line 188) | public void Put(byte value)
method Put (line 196) | public void Put(byte[] data, int offset, int length)
method Put (line 204) | public void Put(byte[] data)
method PutSBytesWithLength (line 212) | public void PutSBytesWithLength(sbyte[] data, int offset, int length)
method PutSBytesWithLength (line 221) | public void PutSBytesWithLength(sbyte[] data)
method PutBytesWithLength (line 230) | public void PutBytesWithLength(byte[] data, int offset, int length)
method PutBytesWithLength (line 239) | public void PutBytesWithLength(byte[] data)
method Put (line 248) | public void Put(bool value)
method PutArray (line 256) | private void PutArray(Array arr, int sz)
method PutArray (line 268) | public void PutArray(float[] value)
method PutArray (line 273) | public void PutArray(double[] value)
method PutArray (line 278) | public void PutArray(long[] value)
method PutArray (line 283) | public void PutArray(ulong[] value)
method PutArray (line 288) | public void PutArray(int[] value)
method PutArray (line 293) | public void PutArray(uint[] value)
method PutArray (line 298) | public void PutArray(ushort[] value)
method PutArray (line 303) | public void PutArray(short[] value)
method PutArray (line 308) | public void PutArray(bool[] value)
method PutArray (line 313) | public void PutArray(string[] value)
method PutArray (line 321) | public void PutArray(string[] value, int maxLength)
method Put (line 329) | public void Put(IPEndPoint endPoint)
method Put (line 335) | public void Put(string value)
method Put (line 354) | public void Put(string value, int maxLength)
method Put (line 377) | public void Put<T>(T obj) where T : INetSerializable
FILE: Assets/Plugins/LiteNetLib/Utils/NetPacketProcessor.cs
class NetPacketProcessor (line 6) | public class NetPacketProcessor
class HashCache (line 8) | private static class HashCache<T>
method NetPacketProcessor (line 19) | public NetPacketProcessor()
method NetPacketProcessor (line 24) | public NetPacketProcessor(int maxStringLength)
method GetHash (line 30) | protected virtual ulong GetHash<T>()
method GetCallbackFromData (line 47) | protected virtual SubscribeDelegate GetCallbackFromData(NetDataReader ...
method WriteHash (line 58) | protected virtual void WriteHash<T>(NetDataWriter writer)
method RegisterNestedType (line 67) | public void RegisterNestedType<T>() where T : struct, INetSerializable
method RegisterNestedType (line 77) | public void RegisterNestedType<T>(Action<NetDataWriter, T> writeDelega...
method RegisterNestedType (line 86) | public void RegisterNestedType<T>(Func<T> constructor) where T : class...
method ReadAllPackets (line 95) | public void ReadAllPackets(NetDataReader reader)
method ReadAllPackets (line 107) | public void ReadAllPackets(NetDataReader reader, object userData)
method ReadPacket (line 118) | public void ReadPacket(NetDataReader reader)
method Send (line 123) | public void Send<T>(NetPeer peer, T packet, DeliveryMethod options) wh...
method SendNetSerializable (line 130) | public void SendNetSerializable<T>(NetPeer peer, T packet, DeliveryMet...
method Send (line 137) | public void Send<T>(NetManager manager, T packet, DeliveryMethod optio...
method SendNetSerializable (line 144) | public void SendNetSerializable<T>(NetManager manager, T packet, Deliv...
method Write (line 151) | public void Write<T>(NetDataWriter writer, T packet) where T : class, ...
method WriteNetSerializable (line 157) | public void WriteNetSerializable<T>(NetDataWriter writer, T packet) wh...
method Write (line 163) | public byte[] Write<T>(T packet) where T : class, new()
method WriteNetSerializable (line 171) | public byte[] WriteNetSerializable<T>(T packet) where T : INetSerializ...
method ReadPacket (line 185) | public void ReadPacket(NetDataReader reader, object userData)
method Subscribe (line 196) | public void Subscribe<T>(Action<T> onReceive, Func<T> packetConstructo...
method Subscribe (line 213) | public void Subscribe<T, TUserData>(Action<T, TUserData> onReceive, Fu...
method SubscribeReusable (line 230) | public void SubscribeReusable<T>(Action<T> onReceive) where T : class,...
method SubscribeReusable (line 247) | public void SubscribeReusable<T, TUserData>(Action<T, TUserData> onRec...
method SubscribeNetSerializable (line 258) | public void SubscribeNetSerializable<T, TUserData>(
method SubscribeNetSerializable (line 270) | public void SubscribeNetSerializable<T>(
method SubscribeNetSerializable (line 282) | public void SubscribeNetSerializable<T, TUserData>(
method SubscribeNetSerializable (line 293) | public void SubscribeNetSerializable<T>(
method RemoveSubscription (line 309) | public bool RemoveSubscription<T>()
FILE: Assets/Plugins/LiteNetLib/Utils/NetSerializer.cs
class InvalidTypeException (line 8) | public class InvalidTypeException : ArgumentException
method InvalidTypeException (line 10) | public InvalidTypeException(string message) : base(message) { }
class ParseException (line 13) | public class ParseException : Exception
method ParseException (line 15) | public ParseException(string message) : base(message) { }
class NetSerializer (line 18) | public class NetSerializer
type CallType (line 20) | private enum CallType
class FastCall (line 27) | private abstract class FastCall<T>
method Init (line 30) | public virtual void Init(MethodInfo getMethod, MethodInfo setMethod,...
method Read (line 31) | public abstract void Read(T inf, NetDataReader r);
method Write (line 32) | public abstract void Write(T inf, NetDataWriter w);
method ReadArray (line 33) | public abstract void ReadArray(T inf, NetDataReader r);
method WriteArray (line 34) | public abstract void WriteArray(T inf, NetDataWriter w);
method ReadList (line 35) | public abstract void ReadList(T inf, NetDataReader r);
method WriteList (line 36) | public abstract void WriteList(T inf, NetDataWriter w);
class FastCallSpecific (line 39) | private abstract class FastCallSpecific<TClass, TProperty> : FastCall<...
method ReadArray (line 48) | public override void ReadArray(TClass inf, NetDataReader r) { throw ...
method WriteArray (line 49) | public override void WriteArray(TClass inf, NetDataWriter w) { throw...
method ReadList (line 50) | public override void ReadList(TClass inf, NetDataReader r) { throw n...
method WriteList (line 51) | public override void WriteList(TClass inf, NetDataWriter w) { throw ...
method ReadArrayHelper (line 53) | protected TProperty[] ReadArrayHelper(TClass inf, NetDataReader r)
method WriteArrayHelper (line 62) | protected TProperty[] WriteArrayHelper(TClass inf, NetDataWriter w)
method ReadListHelper (line 69) | protected List<TProperty> ReadListHelper(TClass inf, NetDataReader r...
method WriteListHelper (line 81) | protected List<TProperty> WriteListHelper(TClass inf, NetDataWriter ...
method Init (line 95) | public override void Init(MethodInfo getMethod, MethodInfo setMethod...
class FastCallSpecificAuto (line 116) | private abstract class FastCallSpecificAuto<TClass, TProperty> : FastC...
method ElementRead (line 118) | protected abstract void ElementRead(NetDataReader r, out TProperty p...
method ElementWrite (line 119) | protected abstract void ElementWrite(NetDataWriter w, ref TProperty ...
method Read (line 121) | public override void Read(TClass inf, NetDataReader r)
method Write (line 128) | public override void Write(TClass inf, NetDataWriter w)
method ReadArray (line 134) | public override void ReadArray(TClass inf, NetDataReader r)
method WriteArray (line 141) | public override void WriteArray(TClass inf, NetDataWriter w)
class FastCallStatic (line 149) | private sealed class FastCallStatic<TClass, TProperty> : FastCallSpeci...
method FastCallStatic (line 154) | public FastCallStatic(Action<NetDataWriter, TProperty> write, Func<N...
method Read (line 160) | public override void Read(TClass inf, NetDataReader r) { Setter(inf,...
method Write (line 161) | public override void Write(TClass inf, NetDataWriter w) { _writer(w,...
method ReadList (line 163) | public override void ReadList(TClass inf, NetDataReader r)
method WriteList (line 179) | public override void WriteList(TClass inf, NetDataWriter w)
method ReadArray (line 187) | public override void ReadArray(TClass inf, NetDataReader r)
method WriteArray (line 195) | public override void WriteArray(TClass inf, NetDataWriter w)
class FastCallStruct (line 204) | private sealed class FastCallStruct<TClass, TProperty> : FastCallSpeci...
method Read (line 208) | public override void Read(TClass inf, NetDataReader r)
method Write (line 214) | public override void Write(TClass inf, NetDataWriter w)
method ReadList (line 220) | public override void ReadList(TClass inf, NetDataReader r)
method WriteList (line 238) | public override void WriteList(TClass inf, NetDataWriter w)
method ReadArray (line 246) | public override void ReadArray(TClass inf, NetDataReader r)
method WriteArray (line 254) | public override void WriteArray(TClass inf, NetDataWriter w)
class FastCallClass (line 263) | private sealed class FastCallClass<TClass, TProperty> : FastCallSpecif...
method FastCallClass (line 266) | public FastCallClass(Func<TProperty> constructor) { _constructor = c...
method Read (line 268) | public override void Read(TClass inf, NetDataReader r)
method Write (line 275) | public override void Write(TClass inf, NetDataWriter w)
method ReadList (line 282) | public override void ReadList(TClass inf, NetDataReader r)
method WriteList (line 304) | public override void WriteList(TClass inf, NetDataWriter w)
method ReadArray (line 312) | public override void ReadArray(TClass inf, NetDataReader r)
method WriteArray (line 323) | public override void WriteArray(TClass inf, NetDataWriter w)
class IntSerializer (line 332) | private class IntSerializer<T> : FastCallSpecific<T, int>
method Read (line 334) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 335) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 336) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 337) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class UIntSerializer (line 340) | private class UIntSerializer<T> : FastCallSpecific<T, uint>
method Read (line 342) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 343) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 344) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 345) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class ShortSerializer (line 348) | private class ShortSerializer<T> : FastCallSpecific<T, short>
method Read (line 350) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 351) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 352) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 353) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class UShortSerializer (line 356) | private class UShortSerializer<T> : FastCallSpecific<T, ushort>
method Read (line 358) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 359) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 360) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 361) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class LongSerializer (line 364) | private class LongSerializer<T> : FastCallSpecific<T, long>
method Read (line 366) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 367) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 368) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 369) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class ULongSerializer (line 372) | private class ULongSerializer<T> : FastCallSpecific<T, ulong>
method Read (line 374) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 375) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 376) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 377) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class ByteSerializer (line 380) | private class ByteSerializer<T> : FastCallSpecific<T, byte>
method Read (line 382) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 383) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 384) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 385) | public override void WriteArray(T inf, NetDataWriter w) { w.PutBytes...
class SByteSerializer (line 388) | private class SByteSerializer<T> : FastCallSpecific<T, sbyte>
method Read (line 390) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 391) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 392) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 393) | public override void WriteArray(T inf, NetDataWriter w) { w.PutSByte...
class FloatSerializer (line 396) | private class FloatSerializer<T> : FastCallSpecific<T, float>
method Read (line 398) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 399) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 400) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 401) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class DoubleSerializer (line 404) | private class DoubleSerializer<T> : FastCallSpecific<T, double>
method Read (line 406) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 407) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 408) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 409) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class BoolSerializer (line 412) | private class BoolSerializer<T> : FastCallSpecific<T, bool>
method Read (line 414) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 415) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 416) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 417) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class CharSerializer (line 420) | private class CharSerializer<T> : FastCallSpecificAuto<T, char>
method ElementWrite (line 422) | protected override void ElementWrite(NetDataWriter w, ref char prop)...
method ElementRead (line 423) | protected override void ElementRead(NetDataReader r, out char prop) ...
class IPEndPointSerializer (line 426) | private class IPEndPointSerializer<T> : FastCallSpecificAuto<T, IPEndP...
method ElementWrite (line 428) | protected override void ElementWrite(NetDataWriter w, ref IPEndPoint...
method ElementRead (line 429) | protected override void ElementRead(NetDataReader r, out IPEndPoint ...
class StringSerializer (line 432) | private class StringSerializer<T> : FastCallSpecific<T, string>
method StringSerializer (line 435) | public StringSerializer(int maxLength) { _maxLength = maxLength > 0 ...
method Read (line 436) | public override void Read(T inf, NetDataReader r) { Setter(inf, r.Ge...
method Write (line 437) | public override void Write(T inf, NetDataWriter w) { w.Put(Getter(in...
method ReadArray (line 438) | public override void ReadArray(T inf, NetDataReader r) { SetterArr(i...
method WriteArray (line 439) | public override void WriteArray(T inf, NetDataWriter w) { w.PutArray...
class EnumByteSerializer (line 442) | private class EnumByteSerializer<T> : FastCall<T>
method EnumByteSerializer (line 446) | public EnumByteSerializer(PropertyInfo property, Type propertyType)
method Read (line 451) | public override void Read(T inf, NetDataReader r) { Property.SetValu...
method Write (line 452) | public override void Write(T inf, NetDataWriter w) { w.Put((byte)Pro...
method ReadArray (line 453) | public override void ReadArray(T inf, NetDataReader r) { throw new I...
method WriteArray (line 454) | public override void WriteArray(T inf, NetDataWriter w) { throw new ...
method ReadList (line 455) | public override void ReadList(T inf, NetDataReader r) { throw new In...
method WriteList (line 456) | public override void WriteList(T inf, NetDataWriter w) { throw new I...
class EnumIntSerializer (line 459) | private class EnumIntSerializer<T> : EnumByteSerializer<T>
method EnumIntSerializer (line 461) | public EnumIntSerializer(PropertyInfo property, Type propertyType) :...
method Read (line 462) | public override void Read(T inf, NetDataReader r) { Property.SetValu...
method Write (line 463) | public override void Write(T inf, NetDataWriter w) { w.Put((int)Prop...
class ClassInfo (line 466) | private sealed class ClassInfo<T>
method ClassInfo (line 472) | public ClassInfo(List<FastCall<T>> serializers)
method Write (line 478) | public void Write(T obj, NetDataWriter writer)
method Read (line 492) | public void Read(T obj, NetDataReader reader)
class CustomType (line 507) | private abstract class CustomType
method Get (line 509) | public abstract FastCall<T> Get<T>();
class CustomTypeStruct (line 512) | private sealed class CustomTypeStruct<TProperty> : CustomType where TP...
method Get (line 514) | public override FastCall<T> Get<T>() { return new FastCallStruct<T, ...
class CustomTypeClass (line 517) | private sealed class CustomTypeClass<TProperty> : CustomType where TPr...
method CustomTypeClass (line 520) | public CustomTypeClass(Func<TProperty> constructor) { _constructor =...
method Get (line 521) | public override FastCall<T> Get<T>() { return new FastCallClass<T, T...
class CustomTypeStatic (line 524) | private sealed class CustomTypeStatic<TProperty> : CustomType
method CustomTypeStatic (line 528) | public CustomTypeStatic(Action<NetDataWriter, TProperty> writer, Fun...
method Get (line 533) | public override FastCall<T> Get<T>() { return new FastCallStatic<T, ...
method RegisterNestedType (line 540) | public void RegisterNestedType<T>() where T : struct, INetSerializable
method RegisterNestedType (line 549) | public void RegisterNestedType<T>(Func<T> constructor) where T : class...
method RegisterNestedType (line 560) | public void RegisterNestedType<T>(Action<NetDataWriter, T> writer, Fun...
method NetSerializer (line 569) | public NetSerializer() : this(0)
method NetSerializer (line 573) | public NetSerializer(int maxStringLength)
method RegisterInternal (line 578) | private ClassInfo<T> RegisterInternal<T>()
method Register (line 671) | public void Register<T>()
method Deserialize (line 682) | public T Deserialize<T>(NetDataReader reader) where T : class, new()
method Deserialize (line 704) | public bool Deserialize<T>(NetDataReader reader, T target) where T : c...
method Serialize (line 724) | public void Serialize<T>(NetDataWriter writer, T obj) where T : class,...
method Serialize (line 734) | public byte[] Serialize<T>(T obj) where T : class, new()
FILE: Assets/Plugins/LiteNetLib/Utils/NtpPacket.cs
class NtpPacket (line 27) | public class NtpPacket
method NtpPacket (line 271) | public NtpPacket() : this(new byte[48])
method NtpPacket (line 281) | internal NtpPacket(byte[] bytes)
method FromServerResponse (line 294) | public static NtpPacket FromServerResponse(byte[] bytes, DateTime dest...
method ValidateRequest (line 299) | internal void ValidateRequest()
method ValidateReply (line 309) | internal void ValidateReply()
method CheckTimestamps (line 322) | private void CheckTimestamps()
method GetDateTime64 (line 334) | private DateTime? GetDateTime64(int offset)
method SetDateTime64 (line 342) | private void SetDateTime64(int offset, DateTime? value)
method GetTimeSpan32 (line 347) | private TimeSpan GetTimeSpan32(int offset)
method GetUInt64BE (line 352) | private ulong GetUInt64BE(int offset)
method SetUInt64BE (line 357) | private void SetUInt64BE(int offset, ulong value)
method GetInt32BE (line 362) | private int GetInt32BE(int offset)
method GetUInt32BE (line 367) | private uint GetUInt32BE(int offset)
method SwapEndianness (line 372) | private static uint SwapEndianness(uint x)
method SwapEndianness (line 377) | private static ulong SwapEndianness(ulong x)
type NtpLeapIndicator (line 387) | public enum NtpLeapIndicator
type NtpMode (line 414) | public enum NtpMode
FILE: Assets/Plugins/LiteNetLib/Utils/NtpRequest.cs
class NtpRequest (line 24) | public sealed class NtpRequest : INetSocketListener
method NtpRequest (line 37) | private NtpRequest(IPEndPoint endPoint, Action<NtpPacket> onRequestCom...
method Create (line 57) | public static NtpRequest Create(IPEndPoint endPoint, Action<NtpPacket>...
method Create (line 67) | public static NtpRequest Create(IPAddress ipAddress, Action<NtpPacket>...
method Create (line 79) | public static NtpRequest Create(string ntpServerAddress, int port, Act...
method Create (line 90) | public static NtpRequest Create(string ntpServerAddress, Action<NtpPac...
method RequestAsync (line 102) | public static async Task<NtpPacket> RequestAsync(string ntpServerAddress)
method Send (line 125) | public void Send()
method Close (line 141) | public void Close()
method OnMessageReceived (line 149) | void INetSocketListener.OnMessageReceived(byte[] data, int length, Soc...
Condensed preview — 169 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (508K chars).
[
{
"path": ".gitignore",
"chars": 1325,
"preview": "# This .gitignore file should be placed at the root of your Unity project directory\n#\n# Get latest from https://github.c"
},
{
"path": ".vscode/settings.json",
"chars": 1347,
"preview": "{\n \"files.exclude\":\n {\n \"**/.DS_Store\":true,\n \"**/.git\":true,\n \"**/.gitignore\":true,\n "
},
{
"path": "Assets/Code/Client/ClientLogic.cs",
"chars": 8452,
"preview": "using System;\nusing System.Net;\nusing System.Net.Sockets;\nusing Code.Shared;\nusing LiteNetLib;\nusing LiteNetLib.Utils;\n"
},
{
"path": "Assets/Code/Client/ClientLogic.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 4a77c76b7885899499706477e4e0eeb4\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Code/Client/ClientPlayer.cs",
"chars": 4649,
"preview": "using Code.Shared;\nusing LiteNetLib;\nusing UnityEngine;\n\nnamespace Code.Client\n{ \n public class ClientPlayer : BasePl"
},
{
"path": "Assets/Code/Client/ClientPlayer.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: aff1c62a30b048c9afcb6b247d10acc6\ntimeCreated: 1552515488"
},
{
"path": "Assets/Code/Client/ClientPlayerManager.cs",
"chars": 3149,
"preview": "using System.Collections.Generic;\nusing Code.Shared;\nusing UnityEngine;\n\nnamespace Code.Client\n{\n public struct Playe"
},
{
"path": "Assets/Code/Client/ClientPlayerManager.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: b654f7e3a7ba40b0860b89829339a4b5\ntimeCreated: 1553432137"
},
{
"path": "Assets/Code/Client/ClientPlayerView.cs",
"chars": 1575,
"preview": "using UnityEngine;\n\nnamespace Code.Client\n{\n public class ClientPlayerView : MonoBehaviour, IPlayerView\n {\n "
},
{
"path": "Assets/Code/Client/ClientPlayerView.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 34c60df172a14e9ba8eeb93c4b0789c8\ntimeCreated: 1552515543"
},
{
"path": "Assets/Code/Client/IPlayerView.cs",
"chars": 94,
"preview": "namespace Code.Client\n{\n public interface IPlayerView\n {\n void Destroy();\n }\n}"
},
{
"path": "Assets/Code/Client/IPlayerView.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 4be69af384c84c7892b27a41f0d59f23\ntimeCreated: 1553427365"
},
{
"path": "Assets/Code/Client/RemotePlayer.cs",
"chars": 2182,
"preview": "using Code.Shared;\nusing UnityEngine;\n\nnamespace Code.Client\n{ \n public class RemotePlayer : BasePlayer\n {\n "
},
{
"path": "Assets/Code/Client/RemotePlayer.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 0a420c02346543379e092fc538932775\ntimeCreated: 1552515495"
},
{
"path": "Assets/Code/Client/RemotePlayerView.cs",
"chars": 799,
"preview": "using UnityEngine;\n\nnamespace Code.Client\n{\n public class RemotePlayerView : MonoBehaviour, IPlayerView\n {\n "
},
{
"path": "Assets/Code/Client/RemotePlayerView.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 79ae69e7e2264cea80924512389f864d\ntimeCreated: 1552862368"
},
{
"path": "Assets/Code/Client/ShootEffect.cs",
"chars": 1680,
"preview": "using System;\nusing Code.Shared;\nusing UnityEngine;\n\npublic class ShootEffect : MonoBehaviour\n{\n [SerializeField] pr"
},
{
"path": "Assets/Code/Client/ShootEffect.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 2b4d80dfb54119b48b368fd5b60c6ab6\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Code/Client/UiController.cs",
"chars": 1112,
"preview": "using Code.Server;\nusing LiteNetLib;\nusing UnityEngine;\nusing UnityEngine.UI;\n\nnamespace Code.Client\n{\n public class"
},
{
"path": "Assets/Code/Client/UiController.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 637a36ad5bdc47f47a5e5c0de52df2fc\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Code/Client.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 154eed4c1661601469c7de37e38b933a\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Code/Server/AntilagSystem.cs",
"chars": 3400,
"preview": "using System.Collections.Generic;\nusing UnityEngine;\n\nnamespace Code.Server\n{\n public struct StateInfo\n {\n "
},
{
"path": "Assets/Code/Server/AntilagSystem.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 601c7fe5599c477ea58e6af0a0d7e91c\ntimeCreated: 1552862682"
},
{
"path": "Assets/Code/Server/ServerLogic.cs",
"chars": 8040,
"preview": "using System.Net;\nusing System.Net.Sockets;\nusing Code.Shared;\nusing LiteNetLib;\nusing LiteNetLib.Utils;\nusing UnityEng"
},
{
"path": "Assets/Code/Server/ServerLogic.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 1e51c98f0b54146429c775c426760c8a\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Code/Server/ServerPlayer.cs",
"chars": 1699,
"preview": "using Code.Shared;\nusing LiteNetLib;\nusing UnityEngine;\n\nnamespace Code.Server\n{\n public class ServerPlayer : BasePla"
},
{
"path": "Assets/Code/Server/ServerPlayer.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 8ad17e029d4b43eeaedf4a29939994e3\ntimeCreated: 1552515641"
},
{
"path": "Assets/Code/Server/ServerPlayerManager.cs",
"chars": 2945,
"preview": "using System.Collections.Generic;\nusing Code.Shared;\nusing LiteNetLib;\nusing UnityEngine;\n\nnamespace Code.Server\n{\n p"
},
{
"path": "Assets/Code/Server/ServerPlayerManager.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: a4f821c063aa411fa470499231c8553a\ntimeCreated: 1553431094"
},
{
"path": "Assets/Code/Server.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 26e8c150dc35a224e965b8abec2e0cfc\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Code/Shared/BasePlayer.cs",
"chars": 2493,
"preview": "using UnityEngine;\n\nnamespace Code.Shared\n{\n public abstract class BasePlayer\n {\n public readonly string N"
},
{
"path": "Assets/Code/Shared/BasePlayer.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 0b3166ab83ce8bc42995be041437971b\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Code/Shared/BasePlayerManager.cs",
"chars": 1142,
"preview": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\nnamespace Code.Shared\n{\n public abstr"
},
{
"path": "Assets/Code/Shared/BasePlayerManager.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 464641a9645748548b39dcb0afed1fd4\ntimeCreated: 1553430803"
},
{
"path": "Assets/Code/Shared/Collisions.cs",
"chars": 1135,
"preview": "namespace Code.Shared\n{\n public static class Collisions\n {\n public static bool CheckIntersection(float x1, "
},
{
"path": "Assets/Code/Shared/Collisions.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 22917542b6524d9085c4f7323d79e532\ntimeCreated: 1553428656"
},
{
"path": "Assets/Code/Shared/Extensions.cs",
"chars": 630,
"preview": "using LiteNetLib.Utils;\nusing UnityEngine;\n\nnamespace Code.Shared\n{\n public static class Extensions\n { \n "
},
{
"path": "Assets/Code/Shared/Extensions.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 774af25bfc0f472287bc2812673fa9d0\ntimeCreated: 1552513976"
},
{
"path": "Assets/Code/Shared/GamePackets.cs",
"chars": 4614,
"preview": "using System;\nusing LiteNetLib.Utils;\nusing UnityEngine;\n\nnamespace Code.Shared\n{\n public enum PacketType : byte\n "
},
{
"path": "Assets/Code/Shared/GamePackets.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: ea1f70e104cd418e8d5e6dc52b99ffb5\ntimeCreated: 1552514144"
},
{
"path": "Assets/Code/Shared/GamePool.cs",
"chars": 825,
"preview": "using System;\n\nnamespace Code.Shared\n{\n public class GamePool<T> where T : class\n {\n private readonly T[] _"
},
{
"path": "Assets/Code/Shared/GamePool.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: 26c97d2cfdfd4ba48e7b065fd13e9c6b\ntimeCreated: 1553454288"
},
{
"path": "Assets/Code/Shared/GameTimer.cs",
"chars": 899,
"preview": "using System;\n\nnamespace Code.Shared\n{\n public struct GameTimer\n {\n private float _maxTime;\n private"
},
{
"path": "Assets/Code/Shared/GameTimer.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: d0c4fc1f8e504c7f910bd163300866e8\ntimeCreated: 1553426365"
},
{
"path": "Assets/Code/Shared/LiteRingBuffer.cs",
"chars": 1729,
"preview": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace Code.Shared\n{\n public class Lite"
},
{
"path": "Assets/Code/Shared/LiteRingBuffer.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: de5c9b10e72c4672ad210ea9f2a7ccad\ntimeCreated: 1553348923"
},
{
"path": "Assets/Code/Shared/LogicTimer.cs",
"chars": 1179,
"preview": "using System;\nusing System.Diagnostics;\n\nnamespace Code.Shared\n{\n public class LogicTimer\n {\n public const "
},
{
"path": "Assets/Code/Shared/LogicTimer.cs.meta",
"chars": 86,
"preview": "fileFormatVersion: 2\r\nguid: c2cf8177f8ed49a4badb018a3dc7c710\r\ntimeCreated: 1552521012"
},
{
"path": "Assets/Code/Shared/NetworkGeneral.cs",
"chars": 611,
"preview": "using System;\n\nnamespace Code.Shared\n{ \n public static class NetworkGeneral\n {\n public const int ProtocolId"
},
{
"path": "Assets/Code/Shared/NetworkGeneral.cs.meta",
"chars": 84,
"preview": "fileFormatVersion: 2\nguid: b8a3ef5ee59f4b75ae44ec2e14551cc7\ntimeCreated: 1552514562"
},
{
"path": "Assets/Code/Shared.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 5b5e02f68e288b14ba1ca61ba84a6e1b\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Code.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 0d17f5c4499ee5c4498aa660551e4658\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Materials/ShootEffectMat.mat",
"chars": 2969,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!21 &2100000\nMaterial:\n serializedVersion: 6\n m_ObjectHideFlags: 0\n m_"
},
{
"path": "Assets/Materials/ShootEffectMat.mat.meta",
"chars": 188,
"preview": "fileFormatVersion: 2\nguid: 1d13efa0bfe6559499d9e8d00237ef50\nNativeFormatImporter:\n externalObjects: {}\n mainObjectFile"
},
{
"path": "Assets/Materials.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: e409e904533a1fc46928119b0f513138\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Plugins/LiteNetLib/BaseChannel.cs",
"chars": 754,
"preview": "using System.Collections.Generic;\n\nnamespace LiteNetLib\n{\n internal abstract class BaseChannel\n {\n public "
},
{
"path": "Assets/Plugins/LiteNetLib/BaseChannel.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 507b99235e7d3fe4387f5cbbc92f03ba\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/ConnectionRequest.cs",
"chars": 3852,
"preview": "using System.Net;\nusing System.Threading;\nusing LiteNetLib.Utils;\n\nnamespace LiteNetLib\n{\n internal enum ConnectionR"
},
{
"path": "Assets/Plugins/LiteNetLib/ConnectionRequest.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: c7f36a00f0b4511498133b6c3c893427\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/INetEventListener.cs",
"chars": 7908,
"preview": "using System.Net;\nusing System.Net.Sockets;\n\nnamespace LiteNetLib\n{\n /// <summary>\n /// Type of message that you r"
},
{
"path": "Assets/Plugins/LiteNetLib/INetEventListener.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 1ad7743bbac7af64e930fcae94fd1a7d\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Layers/Crc32cLayer.cs",
"chars": 1177,
"preview": "using LiteNetLib.Utils;\nusing System;\nusing System.Net;\n\nnamespace LiteNetLib.Layers\n{\n public sealed class Crc32cLa"
},
{
"path": "Assets/Plugins/LiteNetLib/Layers/Crc32cLayer.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 85b0c9ac1a5bf284082c22f13da241e4\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Layers/PacketLayerBase.cs",
"chars": 550,
"preview": "using System.Net;\n\nnamespace LiteNetLib.Layers\n{\n public abstract class PacketLayerBase\n {\n public readonl"
},
{
"path": "Assets/Plugins/LiteNetLib/Layers/PacketLayerBase.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: bf2e5160bd776544693c1c289882a126\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Layers/XorEncryptLayer.cs",
"chars": 1570,
"preview": "using System;\nusing System.Net;\nusing System.Text;\n\nnamespace LiteNetLib.Layers\n{\n public class XorEncryptLayer : Pa"
},
{
"path": "Assets/Plugins/LiteNetLib/Layers/XorEncryptLayer.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 10422bff1ab7eb04894100d55d899764\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Layers.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 370c4c298d0daf74781d2b0aa5420b81\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Plugins/LiteNetLib/NatPunchModule.cs",
"chars": 8947,
"preview": "using System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing LiteNetLib.Utils;\n\nnamespace LiteNet"
},
{
"path": "Assets/Plugins/LiteNetLib/NatPunchModule.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: be2d3965b2909b74a842c90154448111\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/NetConstants.cs",
"chars": 2431,
"preview": "namespace LiteNetLib\n{\n /// <summary>\n /// Sending method type\n /// </summary>\n public enum DeliveryMethod "
},
{
"path": "Assets/Plugins/LiteNetLib/NetConstants.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 53626ac03d7feb74b9b39561430c8c97\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/NetDebug.cs",
"chars": 2535,
"preview": "using System;\nusing System.Diagnostics;\n\nnamespace LiteNetLib\n{\n public class InvalidPacketException : ArgumentExcep"
},
{
"path": "Assets/Plugins/LiteNetLib/NetDebug.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 03c9260e78a794a4b8839e0054f491bd\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/NetManager.cs",
"chars": 62477,
"preview": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Net;\nus"
},
{
"path": "Assets/Plugins/LiteNetLib/NetManager.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 58e96e53edef5bc4ea934b50d4d4c8ba\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/NetPacket.cs",
"chars": 8992,
"preview": "using System;\nusing System.Net;\nusing LiteNetLib.Utils;\n\nnamespace LiteNetLib\n{\n internal enum PacketProperty : byte\n"
},
{
"path": "Assets/Plugins/LiteNetLib/NetPacket.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 7522936b42c769445b2f5d3d2558f5ed\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/NetPacketPool.cs",
"chars": 2230,
"preview": "using System;\nusing System.Threading;\n\nnamespace LiteNetLib\n{\n internal sealed class NetPacketPool\n {\n pri"
},
{
"path": "Assets/Plugins/LiteNetLib/NetPacketPool.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 779e0db7afc7c6e4eb88b849e7c3eced\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/NetPeer.cs",
"chars": 45821,
"preview": "#if DEBUG\n#define STATS_ENABLED\n#endif\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing S"
},
{
"path": "Assets/Plugins/LiteNetLib/NetPeer.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 05dcc73648ef4304f91c2a22996d3652\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/NetSocket.cs",
"chars": 17278,
"preview": "#if UNITY_5_3_OR_NEWER\n#define UNITY\n#if UNITY_IOS && !UNITY_EDITOR\nusing UnityEngine;\n#endif\n#endif\n#if NETSTANDARD || "
},
{
"path": "Assets/Plugins/LiteNetLib/NetSocket.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: bbe4f2df734c49848b0f4b3f3167bb38\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/NetStatistics.cs",
"chars": 2678,
"preview": "using System.Threading;\n\nnamespace LiteNetLib\n{\n public sealed class NetStatistics \n {\n private long _pack"
},
{
"path": "Assets/Plugins/LiteNetLib/NetStatistics.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 2c91a08025fc3144ea528aa15dabe0e5\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/NetUtils.cs",
"chars": 7269,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Net.NetworkInfo"
},
{
"path": "Assets/Plugins/LiteNetLib/NetUtils.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: f348c24015ad55140beb9171b51c7540\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/ReliableChannel.cs",
"chars": 11748,
"preview": "using System;\n\nnamespace LiteNetLib\n{\n internal sealed class ReliableChannel : BaseChannel\n {\n private stru"
},
{
"path": "Assets/Plugins/LiteNetLib/ReliableChannel.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: eee991fc4aaa1f3418cf4ac524154427\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/SequencedChannel.cs",
"chars": 3743,
"preview": "using System;\n\nnamespace LiteNetLib\n{\n internal sealed class SequencedChannel : BaseChannel\n {\n private int"
},
{
"path": "Assets/Plugins/LiteNetLib/SequencedChannel.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 3ee3332c6d2734f4980328c17ae0a71d\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/CRC32C.cs",
"chars": 4116,
"preview": "#if NETCOREAPP3_0\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Intrinsics.X86;\n#endif\n\nname"
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/CRC32C.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 082cd999e5284844d82fd3f7ee0a9ede\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/FastBitConverter.cs",
"chars": 3861,
"preview": "using System.Runtime.InteropServices;\n\nnamespace LiteNetLib.Utils\n{\n public static class FastBitConverter\n {\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/FastBitConverter.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 95d17deeb9f33bf4abfb7ad06ebcc80b\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/INetSerializable.cs",
"chars": 176,
"preview": "namespace LiteNetLib.Utils\n{\n public interface INetSerializable\n {\n void Serialize(NetDataWriter writer);\n"
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/INetSerializable.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 51a5959e04e00a549bb5d9e37d9d6053\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NetDataReader.cs",
"chars": 17615,
"preview": "using System;\nusing System.Net;\nusing System.Text;\n\nnamespace LiteNetLib.Utils\n{\n public class NetDataReader\n {\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NetDataReader.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: a46d434c453198440bcb27e10f692391\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NetDataWriter.cs",
"chars": 10736,
"preview": "using System;\nusing System.Net;\nusing System.Text;\n\nnamespace LiteNetLib.Utils\n{\n public class NetDataWriter\n {\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NetDataWriter.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: c0ffde081f520024ab3d374372df31ff\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NetPacketProcessor.cs",
"chars": 12177,
"preview": "using System;\nusing System.Collections.Generic;\n\nnamespace LiteNetLib.Utils\n{\n public class NetPacketProcessor\n {"
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NetPacketProcessor.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: b42e8b07a748cfa49b39546f3d747abe\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NetSerializer.cs",
"chars": 31994,
"preview": "using System;\nusing System.Reflection;\nusing System.Collections.Generic;\nusing System.Net;\n\nnamespace LiteNetLib.Utils\n"
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NetSerializer.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 2369079a03e234a459eac1fb0d7f9ffa\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NtpPacket.cs",
"chars": 17577,
"preview": "using System;\n\nnamespace LiteNetLib.Utils\n{\n /// <summary>\n /// Represents RFC4330 SNTP packet used for communica"
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NtpPacket.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 83e4dc419f776ab498b9af922a0a4b47\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NtpRequest.cs",
"chars": 6433,
"preview": "using System;\nusing System.Net;\nusing System.Net.Sockets;\n\n#if NETSTANDARD || NETCOREAPP\nusing System.Threading.Tasks;\n"
},
{
"path": "Assets/Plugins/LiteNetLib/Utils/NtpRequest.cs.meta",
"chars": 243,
"preview": "fileFormatVersion: 2\nguid: 2c10cb27cfa72e24ea36cc68ac7fd60d\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n "
},
{
"path": "Assets/Plugins/LiteNetLib/Utils.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: ebacf1eb87716ee49b6fcb20c0704ac6\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Plugins/LiteNetLib.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 25c77b3ad615d2d42a26744ab3ce1f23\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Plugins.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 65324f827c8ba984c87f6eb3977105b3\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Prefabs/ClientPlayerPrefab.prefab",
"chars": 6085,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &151283213529981653\nGameObject:\n m_ObjectHideFlags: 0\n m_Correspondi"
},
{
"path": "Assets/Prefabs/ClientPlayerPrefab.prefab.meta",
"chars": 154,
"preview": "fileFormatVersion: 2\nguid: 4a0b43f6f6aa8d94885a8928324663ae\nPrefabImporter:\n externalObjects: {}\n userData: \n assetBu"
},
{
"path": "Assets/Prefabs/RemotePlayerPrefab.prefab",
"chars": 2647,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &151283213529981653\nGameObject:\n m_ObjectHideFlags: 0\n m_Correspondi"
},
{
"path": "Assets/Prefabs/RemotePlayerPrefab.prefab.meta",
"chars": 154,
"preview": "fileFormatVersion: 2\nguid: 286a2aeb6d53b6140a311cbe617d000f\nPrefabImporter:\n externalObjects: {}\n userData: \n assetBu"
},
{
"path": "Assets/Prefabs/ShootEffect.prefab",
"chars": 11025,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &10134456475359289\nGameObject:\n m_ObjectHideFlags: 0\n m_Correspondin"
},
{
"path": "Assets/Prefabs/ShootEffect.prefab.meta",
"chars": 154,
"preview": "fileFormatVersion: 2\nguid: 34cd9b45af10c374daabd0023264392f\nPrefabImporter:\n externalObjects: {}\n userData: \n assetBu"
},
{
"path": "Assets/Prefabs.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 38a006a4ce1e703499c4c180ac138f0e\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Scenes/SampleScene.unity",
"chars": 40295,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!29 &1\nOcclusionCullingSettings:\n m_ObjectHideFlags: 0\n serializedVersi"
},
{
"path": "Assets/Scenes/SampleScene.unity.meta",
"chars": 155,
"preview": "fileFormatVersion: 2\nguid: 0ded2f7f4591ec7439b78ecd3eeabd99\nDefaultImporter:\n externalObjects: {}\n userData: \n assetB"
},
{
"path": "Assets/Scenes.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 934d0155eefb63546bde5bf781f772f2\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "Assets/Sounds/death1.ogg.meta",
"chars": 458,
"preview": "fileFormatVersion: 2\nguid: 13bf3bab902d9a64ba3936703ad369fe\nAudioImporter:\n externalObjects: {}\n serializedVersion: 6\n"
},
{
"path": "Assets/Sounds/death2.ogg.meta",
"chars": 458,
"preview": "fileFormatVersion: 2\nguid: db647400cd797af43b96ed8a210e4caf\nAudioImporter:\n externalObjects: {}\n serializedVersion: 6\n"
},
{
"path": "Assets/Sounds/death3.ogg.meta",
"chars": 458,
"preview": "fileFormatVersion: 2\nguid: 6f08295468d9a2f43a53f7826f09b3f2\nAudioImporter:\n externalObjects: {}\n serializedVersion: 6\n"
},
{
"path": "Assets/Sounds/hit1.ogg.meta",
"chars": 458,
"preview": "fileFormatVersion: 2\nguid: 2db6c6b7d938d6445a1506241e464a60\nAudioImporter:\n externalObjects: {}\n serializedVersion: 6\n"
},
{
"path": "Assets/Sounds/hit2.ogg.meta",
"chars": 458,
"preview": "fileFormatVersion: 2\nguid: 7183751adb74f494d8c1760f20588846\nAudioImporter:\n externalObjects: {}\n serializedVersion: 6\n"
},
{
"path": "Assets/Sounds/hit3.ogg.meta",
"chars": 458,
"preview": "fileFormatVersion: 2\nguid: 71216075a33d8b747a2e1cf162174c02\nAudioImporter:\n externalObjects: {}\n serializedVersion: 6\n"
},
{
"path": "Assets/Sounds/shoot1.ogg.meta",
"chars": 458,
"preview": "fileFormatVersion: 2\nguid: 55dee76dad95e3d4485c01b3bffe0cc3\nAudioImporter:\n externalObjects: {}\n serializedVersion: 6\n"
},
{
"path": "Assets/Sounds/shoot2.ogg.meta",
"chars": 458,
"preview": "fileFormatVersion: 2\nguid: 8fa59a9269be9fb43992ae257a830baf\nAudioImporter:\n externalObjects: {}\n serializedVersion: 6\n"
},
{
"path": "Assets/Sounds/shoot3.ogg.meta",
"chars": 458,
"preview": "fileFormatVersion: 2\nguid: c5fb28979014b6743a96f027422cd352\nAudioImporter:\n externalObjects: {}\n serializedVersion: 6\n"
},
{
"path": "Assets/Sounds.meta",
"chars": 172,
"preview": "fileFormatVersion: 2\nguid: 660d458fea5aa5f458b37717489c7b36\nfolderAsset: yes\nDefaultImporter:\n externalObjects: {}\n us"
},
{
"path": "LICENSE",
"chars": 1069,
"preview": "MIT License\n\nCopyright (c) 2019 Ruslan Pyrch\n\nPermission is hereby granted, free of charge, to any person obtaining a co"
},
{
"path": "Packages/manifest.json",
"chars": 351,
"preview": "{\n \"dependencies\": {\n \"com.unity.ide.rider\": \"3.0.15\",\n \"com.unity.ide.visualstudio\": \"2.0.16\",\n \"com.unity.id"
},
{
"path": "Packages/packages-lock.json",
"chars": 2177,
"preview": "{\n \"dependencies\": {\n \"com.unity.ext.nunit\": {\n \"version\": \"1.0.6\",\n \"depth\": 1,\n \"source\": \"registry"
},
{
"path": "ProjectSettings/AudioManager.asset",
"chars": 360,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!11 &1\nAudioManager:\n m_ObjectHideFlags: 0\n m_Volume: 1\n Rolloff Scale"
},
{
"path": "ProjectSettings/ClusterInputManager.asset",
"chars": 114,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!236 &1\nClusterInputManager:\n m_ObjectHideFlags: 0\n m_Inputs: []\n"
},
{
"path": "ProjectSettings/DynamicsManager.asset",
"chars": 1075,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!55 &1\nPhysicsManager:\n m_ObjectHideFlags: 0\n serializedVersion: 8\n m_"
},
{
"path": "ProjectSettings/EditorBuildSettings.asset",
"chars": 160,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1045 &1\nEditorBuildSettings:\n m_ObjectHideFlags: 0\n serializedVersion:"
},
{
"path": "ProjectSettings/EditorSettings.asset",
"chars": 1103,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!159 &1\nEditorSettings:\n m_ObjectHideFlags: 0\n serializedVersion: 9\n m"
},
{
"path": "ProjectSettings/GraphicsSettings.asset",
"chars": 2234,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!30 &1\nGraphicsSettings:\n m_ObjectHideFlags: 0\n serializedVersion: 13\n "
},
{
"path": "ProjectSettings/InputManager.asset",
"chars": 5805,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!13 &1\nInputManager:\n m_ObjectHideFlags: 0\n serializedVersion: 2\n m_Ax"
},
{
"path": "ProjectSettings/MemorySettings.asset",
"chars": 1192,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!387306366 &1\nMemorySettings:\n m_ObjectHideFlags: 0\n m_EditorMemorySett"
},
{
"path": "ProjectSettings/NavMeshAreas.asset",
"chars": 1308,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!126 &1\nNavMeshProjectSettings:\n m_ObjectHideFlags: 0\n serializedVersio"
},
{
"path": "ProjectSettings/NetworkManager.asset",
"chars": 151,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!149 &1\nNetworkManager:\n m_ObjectHideFlags: 0\n m_DebugLevel: 0\n m_Send"
},
{
"path": "ProjectSettings/PackageManagerSettings.asset",
"chars": 928,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &1\nMonoBehaviour:\n m_ObjectHideFlags: 61\n m_CorrespondingSourceObj"
},
{
"path": "ProjectSettings/Physics2DSettings.asset",
"chars": 2028,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!19 &1\nPhysics2DSettings:\n m_ObjectHideFlags: 0\n serializedVersion: 4\n "
},
{
"path": "ProjectSettings/PresetManager.asset",
"chars": 342,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1386491679 &1\nPresetManager:\n m_ObjectHideFlags: 0\n m_DefaultList:\n -"
},
{
"path": "ProjectSettings/ProjectSettings.asset",
"chars": 18507,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!129 &1\nPlayerSettings:\n m_ObjectHideFlags: 0\n serializedVersion: 20\n "
},
{
"path": "ProjectSettings/ProjectVersion.txt",
"chars": 83,
"preview": "m_EditorVersion: 2021.3.8f1\nm_EditorVersionWithRevision: 2021.3.8f1 (b30333d56e81)\n"
},
{
"path": "ProjectSettings/QualitySettings.asset",
"chars": 6460,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!47 &1\nQualitySettings:\n m_ObjectHideFlags: 0\n serializedVersion: 5\n m"
},
{
"path": "ProjectSettings/TagManager.asset",
"chars": 378,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!78 &1\nTagManager:\n serializedVersion: 2\n tags: []\n layers:\n - Defaul"
},
{
"path": "ProjectSettings/TimeManager.asset",
"chars": 195,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!5 &1\nTimeManager:\n m_ObjectHideFlags: 0\n Fixed Timestep: 0.02\n Maximu"
},
{
"path": "ProjectSettings/UnityConnectSettings.asset",
"chars": 853,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!310 &1\nUnityConnectSettings:\n m_ObjectHideFlags: 0\n serializedVersion:"
},
{
"path": "ProjectSettings/VFXManager.asset",
"chars": 273,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!937362698 &1\nVFXManager:\n m_ObjectHideFlags: 0\n m_IndirectShader: {fil"
},
{
"path": "ProjectSettings/VersionControlSettings.asset",
"chars": 188,
"preview": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!890905787 &1\nVersionControlSettings:\n m_ObjectHideFlags: 0\n m_Mode: Vi"
},
{
"path": "ProjectSettings/XRSettings.asset",
"chars": 158,
"preview": "{\n \"m_SettingKeys\": [\n \"VR Device Disabled\",\n \"VR Device User Alert\"\n ],\n \"m_SettingValues\": [\n "
},
{
"path": "ProjectSettings/boot.config",
"chars": 0,
"preview": ""
},
{
"path": "README.md",
"chars": 251,
"preview": "# NetGameExample\nExample simple game with LiteNetLib (work in progress)\n\nTop down 2d network shooter\n\nDone:\n* Authoritat"
}
]
// ... and 9 more files (download for full content)
About this extraction
This page contains the full source code of the RevenantX/NetGameExample GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 169 files (470.1 KB), approximately 126.8k tokens, and a symbol index with 828 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.