Network Library Documentation
Loading...
Searching...
No Matches
Client.TCP Class Reference

Handles TCP connection. More...

Public Member Functions

void Connect ()
 Establishes a TCP connection to the server and begins receiving data.
void Send (Packet Packet)
 Sends a packet to the server using TCP.
void Disconnect ()
 Disconnects the TCP connection and clears the buffers.

Public Attributes

TcpClient Socket

Private Member Functions

bool Handler (byte[] data)
 Handles received raw byte data from the server.
void ConnectCallback (IAsyncResult result)
 Callback triggered after attempting to connect to the server by TCP. Initializes TLS if enabled, sets up the stream, and begins reading data.
void ReceiveCallback (IAsyncResult result)
 Callback for receiving data over the TCP. Reads data into the data buffer, manages it by Handler and continues reading.

Static Private Member Functions

static bool ValidateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 Validates the server's SSL/TLS certificate. Returns true if the certificate is valid; else writes error and returns false.

Private Attributes

Stream Stream
byte[] receiveBuffer
Packet receivedPacket

Detailed Description

Handles TCP connection.

Definition at line 291 of file Client.cs.

Member Function Documentation

◆ Connect()

void Client.TCP.Connect ( )

Establishes a TCP connection to the server and begins receiving data.

Definition at line 300 of file Client.cs.

301 {
302 if(Client.instance.GetUsername() == "")
303 {
304 System.Random rng = new System.Random();
305 int rand = rng.Next(1000);
306 Client.instance.SetUsername("Guest" + rand.ToString());
307 }
308 Socket = new TcpClient
309 {
310 ReceiveBufferSize = DefaultBufferSize,
311 SendBufferSize = DefaultBufferSize
312 };
313 receiveBuffer = new byte[DefaultBufferSize];
314 Socket.BeginConnect(Client.instance.defaultNetworkSettings.ipAddress, Client.instance.defaultNetworkSettings.port, ConnectCallback, Socket); // zacne asynchronne pripojenie k serveru, ak uspesne da callback
315 }

◆ ConnectCallback()

void Client.TCP.ConnectCallback ( IAsyncResult result)
private

Callback triggered after attempting to connect to the server by TCP. Initializes TLS if enabled, sets up the stream, and begins reading data.

Definition at line 401 of file Client.cs.

402 {
403 try
404 {
405 Socket.EndConnect(result);
406 if (!Socket.Connected)
407 {
408 return;
409 }
410 if (Client.instance.defaultNetworkSettings.useTLS == true)
411 {
412 SslStream ScStream = new SslStream(Socket.GetStream(), false, ValidateServerCertificate);
413 ScStream.AuthenticateAsClient(Client.instance.defaultNetworkSettings.ipAddress);
414
415 receiveBuffer = new byte[Client.DefaultBufferSize];
416 receivedPacket = new Packet();
417 Stream = ScStream;
418 } else
419 {
420 Stream = Socket.GetStream();
421 receiveBuffer = new byte[Client.DefaultBufferSize];
422 receivedPacket = new Packet();
423 }
424 Stream.BeginRead(receiveBuffer, 0, Client.DefaultBufferSize, ReceiveCallback, null);
425 Client.instance.isConnected = true;
426 ThreadsController.StartOnMainThread(() =>
427 {
428 Client.instance.OnConnected?.Invoke();
429 });
430 }
431 catch (Exception ex)
432 {
433 Debug.LogError($"Error during SSL/TLS handshake: {ex.Message}");
434 ThreadsController.StartOnMainThread(() =>
435 {
436 Client.instance.OnConnectionFailed?.Invoke($"Error during SSL/TLS handshake: {ex.Message}");
437 });
438 Disconnect();
439 }
440 }

◆ Disconnect()

void Client.TCP.Disconnect ( )

Disconnects the TCP connection and clears the buffers.

Definition at line 336 of file Client.cs.

337 {
338 Stream = null;
339 receivedPacket = null;
340 receiveBuffer = null;
341 Socket = null;
342 }

◆ Handler()

bool Client.TCP.Handler ( byte[] data)
private

Handles received raw byte data from the server.

Definition at line 358 of file Client.cs.

359 {
360 int packetLength = 0;
361 receivedPacket.AddBytesToBuffers(data);
362 if (receivedPacket.UnreadLength() >= 4)
363 {
364 packetLength = receivedPacket.ReadInt();
365 if (packetLength <= 0)
366 {
367 return true;
368 }
369 }
370 while (packetLength > 0 && packetLength <= receivedPacket.UnreadLength())
371 {
372 byte[] packetBytes = receivedPacket.ReadBytes(packetLength);
373 ThreadsController.StartOnMainThread(() =>
374 {
375 Packet packet = new Packet(packetBytes);
376 int packetId = packet.ReadInt();
377 PacketAction(packetId, packet);
378 });
379 packetLength = 0;
380 if (receivedPacket.UnreadLength() >= 4)
381 {
382 packetLength = receivedPacket.ReadInt();
383 if (packetLength <= 0)
384 {
385 return true;
386 }
387 }
388 }
389 if (packetLength <= 1)
390 {
391 return true;
392 }
393 return false;
394 }
int ReadInt(bool changeReadPosition=true)
Read int data.
Definition Packet.cs:80

◆ ReceiveCallback()

void Client.TCP.ReceiveCallback ( IAsyncResult result)
private

Callback for receiving data over the TCP. Reads data into the data buffer, manages it by Handler and continues reading.

Definition at line 445 of file Client.cs.

446 {
447 try
448 {
449 int dataLength = Stream.EndRead(result);
450 if (dataLength <= 0)
451 {
452 instance.Disconnect();
453 return;
454 }
455 byte[] data = new byte[dataLength];
456 Array.Copy(receiveBuffer, data, dataLength);
457 receivedPacket.ClearPacket(Handler(data));
458 Stream.BeginRead(receiveBuffer, 0, DefaultBufferSize, ReceiveCallback, null);
459 }
460 catch (Exception ex) {
461 Debug.LogError($"Error connecting {ex}");
462 }
463 }

◆ Send()

void Client.TCP.Send ( Packet Packet)

Sends a packet to the server using TCP.

Definition at line 319 of file Client.cs.

320 {
321 try
322 {
323 if (Socket != null)
324 {
325 Stream.BeginWrite(Packet.ConvertToArray(), 0, Packet.DataLength(), null, null);
326 }
327 }
328 catch (Exception _ex)
329 {
330 Debug.LogError($"Error sending data to server via TCP: {_ex}");
331 }
332 }
byte[] ConvertToArray()
Definition Packet.cs:287
int DataLength()
Definition Packet.cs:300

◆ ValidateServerCertificate()

bool Client.TCP.ValidateServerCertificate ( object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors )
staticprivate

Validates the server's SSL/TLS certificate. Returns true if the certificate is valid; else writes error and returns false.

Definition at line 346 of file Client.cs.

347 {
348 if (sslPolicyErrors == SslPolicyErrors.None)
349 {
350 return true;
351 }
352 Debug.LogError($"SSL/TLS validation error: {sslPolicyErrors}");
353 return false;
354 }

Member Data Documentation

◆ receiveBuffer

byte [] Client.TCP.receiveBuffer
private

Definition at line 295 of file Client.cs.

◆ receivedPacket

Packet Client.TCP.receivedPacket
private

Definition at line 296 of file Client.cs.

◆ Socket

TcpClient Client.TCP.Socket

Definition at line 293 of file Client.cs.

◆ Stream

Stream Client.TCP.Stream
private

Definition at line 294 of file Client.cs.