123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.Net;
- using System.Net.Sockets;
- using System;
-
- public class Client : MonoBehaviour
- {
- public static Client instance;
- public static int dataBufferSize = 4096;
-
- public string ip = "127.0.0.1";
- public int port = 26950;
- public int myId = 0;
- public TCP tcp;
- public UDP udp;
-
- private bool isConnected = false;
- private delegate void PacketHandler(Packet _packet);
- private static Dictionary<int, PacketHandler> packetHandlers;
-
- private void Awake()
- {
- if (instance == null)
- {
- instance = this;
- }
- else if (instance != this)
- {
- Debug.Log("Instance already exists. Destroying object !");
- Destroy(this);
- }
- }
-
- private void Start()
- {
- tcp = new TCP();
- udp = new UDP();
- }
-
- private void OnApplicationQuit()
- {
- Disconnect();
- }
-
- public void ConnectToServer()
- {
- InitializeClientData();
-
- isConnected = true;
- tcp.Connect();
- }
-
- public class TCP
- {
- public TcpClient socket;
-
- private NetworkStream stream;
- private Packet receivedData;
- private byte[] receiveBuffer;
-
- public void Connect()
- {
- socket = new TcpClient
- {
- ReceiveBufferSize = dataBufferSize,
- SendBufferSize = dataBufferSize
- };
-
- receiveBuffer = new byte[dataBufferSize];
- socket.BeginConnect(instance.ip, instance.port, ConnectCallback, socket);
- }
-
- private void ConnectCallback(IAsyncResult _result)
- {
- socket.EndConnect(_result);
- Debug.Log("test");
- if (!socket.Connected)
- {
- Debug.Log("Couldn't connect");
- return;
- }
-
- stream = socket.GetStream();
-
- receivedData = new Packet();
-
- stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
- }
-
- public void SendData(Packet _packet)
- {
- try
- {
- if (socket != null)
- {
- stream.BeginWrite(_packet.ToArray(), 0, _packet.Length(), null, null);
- }
- }
- catch (Exception _ex)
- {
- Debug.Log($"Error sending data to server via TCP : {_ex}");
- }
- }
-
- private void ReceiveCallback(IAsyncResult _result)
- {
- try
- {
- int _byteLength = stream.EndRead(_result);
- if (_byteLength <= 0)
- {
- instance.Disconnect();
- return;
- }
-
- byte[] _data = new byte[_byteLength];
- Array.Copy(receiveBuffer, _data, _byteLength);
-
- receivedData.Reset(HandleData(_data));
- stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
-
- }
- catch (Exception)
- {
- Disconnect();
- }
- }
-
- private bool HandleData(byte[] _data)
- {
- int _packetLength = 0;
-
- receivedData.SetBytes(_data);
-
- if (receivedData.UnreadLength() >= 4)
- {
- _packetLength = receivedData.ReadInt();
- if (_packetLength <= 0)
- {
- return true;
- }
- }
-
- while (_packetLength > 0 && _packetLength <= receivedData.UnreadLength())
- {
- byte[] _packetBytes = receivedData.ReadBytes(_packetLength);
- ThreadManager.ExecuteOnMainThread(() =>
- {
- using (Packet _packet = new Packet(_packetBytes))
- {
- int _packetId = _packet.ReadInt();
- packetHandlers[_packetId](_packet);
- }
- });
-
- _packetLength = 0;
- if (receivedData.UnreadLength() >= 4)
- {
- _packetLength = receivedData.ReadInt();
- if (_packetLength <= 0)
- {
- return true;
- }
- }
- }
-
- if (_packetLength <= 1)
- {
- return true;
- }
-
- return false;
- }
-
- private void Disconnect()
- {
- instance.Disconnect();
-
- stream = null;
- receivedData = null;
- receiveBuffer = null;
- socket = null;
- }
- }
-
- public class UDP
- {
- public UdpClient socket;
- public IPEndPoint endPoint;
-
- public void Connect(int _localPort)
- {
- socket = new UdpClient(_localPort);
-
- endPoint = new IPEndPoint(IPAddress.Parse(instance.ip), instance.port);
- socket.Connect(endPoint);
- socket.BeginReceive(ReceiveCallback, null);
-
- using (Packet _packet = new Packet())
- {
- SendData(_packet);
- }
- }
-
- public void SendData(Packet _packet)
- {
- try
- {
- _packet.InsertInt(instance.myId);
- if (socket != null)
- {
- socket.BeginSend(_packet.ToArray(), _packet.Length(), null, null);
- }
- }
- catch (Exception _ex)
- {
- Debug.Log($"Error sending data to server via UDP : {_ex}");
- }
- }
-
- private void ReceiveCallback(IAsyncResult _result)
- {
- try
- {
- byte[] _data = socket.EndReceive(_result, ref endPoint);
- socket.BeginReceive(ReceiveCallback, null);
-
- if (_data.Length < 4)
- {
- instance.Disconnect();
- return;
- }
-
- HandleData(_data);
- }
- catch (Exception)
- {
- Disconnect();
- }
- }
-
- private void HandleData(byte[] _data)
- {
- using (Packet _packet = new Packet(_data))
- {
- int _packetLength = _packet.ReadInt();
- _data = _packet.ReadBytes(_packetLength);
- }
-
- ThreadManager.ExecuteOnMainThread(() =>
- {
- using (Packet _packet = new Packet(_data))
- {
- int _packetId = _packet.ReadInt();
- packetHandlers[_packetId](_packet);
- }
- });
- }
-
- private void Disconnect()
- {
- instance.Disconnect();
-
- endPoint = null;
- socket = null;
- }
- }
-
- private void InitializeClientData()
- {
- packetHandlers = new Dictionary<int, PacketHandler>()
- {
- { (int)ServerPackets.welcome, ClientHandle.Welcome },
- { (int)ServerPackets.spawnPlayer, ClientHandle.SpawnPlayer },
- { (int)ServerPackets.playerPosition, ClientHandle.PlayerPosition },
- { (int)ServerPackets.playerRotation, ClientHandle.PlayerRotation },
- { (int)ServerPackets.playerDisconnected, ClientHandle.PlayerDisconnected },
- { (int)ServerPackets.playerHealth, ClientHandle.PlayerHealth },
- { (int)ServerPackets.playerRespawned, ClientHandle.PlayerRespawned }
-
- };
- Debug.Log("Initialized packets.");
- }
-
- private void Disconnect()
- {
- if (isConnected)
- {
- isConnected = false;
- tcp.socket.Close();
- udp.socket.Close();
-
- Debug.Log("Disconnected from server");
- }
- }
- }
|