public async Task ServerListenThreadAction(string hostname, int port) { var client = default(TcpClient); try { client = new TcpClient(hostname, port); Logger.Info($"Connected to [{hostname}:{port}]"); var stream = client.GetStream(); Logger.Info($"Sending [{nameof(PacketOpcode.AnnounceAlive)}] packet to server."); var announceAlive = PacketMaker.GetPacketFromOpcode(PacketOpcode.AnnounceAlive); await NetData.WritePacketsAsync(stream, announceAlive); Logger.Info($"Waiting on response..."); var response = await NetData.ReadPacketAsync(stream, client.ReceiveBufferSize); if (response.Opcode == PacketOpcode.AnnounceAlive_Response) { Logger.Info($"Received valid {nameof(PacketOpcode.AnnounceAlive_Response)} packet from server."); OnServerConnected?.Invoke(); } else { Logger.Error($"Failed handshake with server. Expected [{nameof(PacketOpcode.AnnounceAlive_Response)}] but received [{response.Opcode}] instead."); } } catch (ThreadInterruptedException e) { Logger.Error($"{nameof(ServerListenThreadAction)} thread was interrupted and connection will be forcibly closed by us."); } finally { if (client != null && client.Connected) { client.Close(); } } }