Files
Client-Server-Apps/Client App/Program.cs
2026-04-10 23:05:59 +04:00

106 lines
3.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class Client
{
private static TcpClient client;
private static NetworkStream stream;
private static string currentGroup = "all";
static void Main()
{
Console.Write("Введите ваше имя: ");
string name = Console.ReadLine();
string serverIp = "127.0.0.1";
int port = 8888;
try
{
client = new TcpClient();
client.Connect(serverIp, port);
stream = client.GetStream();
// Отправляем имя
byte[] nameData = Encoding.UTF8.GetBytes(name);
stream.Write(nameData, 0, nameData.Length);
Console.WriteLine($"Добро пожаловать, {name}!");
// Поток для приема сообщений
Thread receiveThread = new Thread(ReceiveMessages);
receiveThread.Start();
// Циклическая отправка сообщений
while (true)
{
Console.Write($"[Группа: {currentGroup}] Введите сообщение: ");
string text = Console.ReadLine();
if (text.ToLower() == "exit")
break;
else if (text.StartsWith("/join "))
{
currentGroup = text.Substring(6);
string command = $"/group {currentGroup}";
byte[] data = Encoding.UTF8.GetBytes(command);
stream.Write(data, 0, data.Length);
}
else if (text.StartsWith("/groups"))
{
// Запрос списка групп и клиентов
byte[] data = Encoding.UTF8.GetBytes("/groups");
stream.Write(data, 0, data.Length);
}
else
{
string message = $"/msg {currentGroup} {text}";
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
}
}
}
catch (Exception e)
{
Console.WriteLine($"Ошибка: {e.Message}");
}
finally
{
stream?.Close();
client?.Close();
}
}
private static void ReceiveMessages()
{
byte[] buffer = new byte[4096];
try
{
while (true)
{
int bytes = stream.Read(buffer, 0, buffer.Length);
if (bytes == 0) break;
string response = Encoding.UTF8.GetString(buffer, 0, bytes);
if (response.StartsWith("/clients "))
{
Console.WriteLine($"\n=== Список клиентов и групп ===");
Console.WriteLine(response.Substring(9));
Console.WriteLine("================================");
}
else
{
Console.WriteLine($"\n[Сообщение]: {response}");
}
Console.Write($"[Группа: {currentGroup}] Введите сообщение: ");
}
}
catch
{
Console.WriteLine("\nСоединение с сервером потеряно");
}
}
}