Uploaded by Арина Кисвянцева

Лабораторная работа №2. Сервер-клиент

advertisement
server.cs:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static int solvedEquationsCount = 0;
static HashSet<string> usedClientIds = new HashSet<string>();
static void Main(string[] args)
{
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Any, 8888);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Bind(ipPoint);
socket.Listen();
Console.WriteLine("Сервер запущен ");
while (true)
{
Socket client = socket.Accept();
string clientId = GenerateClientId();
usedClientIds.Add(clientId);
Console.WriteLine($"Клиент подключен (ID: {clientId})");
byte[] buffer = new byte[512];
int bytesReceived = client.Receive(buffer);
string equation = Encoding.UTF8.GetString(buffer, 0, bytesReceived);
Console.WriteLine($"Уравнение от клиента (ID: {clientId}): {equation}");
string[] coeffs = equation.Split(' ');
if (coeffs.Length != 3)
{
client.Send(Encoding.UTF8.GetBytes("Ошибка: Необходимо передать 3 коэффициента"));
client.Shutdown(SocketShutdown.Both);
client.Close();
continue;
}
if (!double.TryParse(coeffs[0], out double a) || !double.TryParse(coeffs[1], out double b) || !double.TryParse(coeffs[2], out
double c))
{
client.Send(Encoding.UTF8.GetBytes("Ошибка: Некорректные коэффициенты"));
client.Shutdown(SocketShutdown.Both);
client.Close();
continue;
}
double discriminant = b * b - 4 * a * c;
if (discriminant < 0)
{
client.Send(Encoding.UTF8.GetBytes("Уравнение не имеет действительных корней"));
Console.WriteLine("Уравнение не имеет действительных корней");
}
else if (discriminant == 0)
{
double root = (-b) / (2 * a);
client.Send(Encoding.UTF8.GetBytes($"Уравнение имеет один корень: {FormatRoot(root)}"));
Console.WriteLine($"Уравнение имеет один корень: {FormatRoot(root)}");
}
else
{
double root1 = (-b + Math.Sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.Sqrt(discriminant)) / (2 * a);
client.Send(Encoding.UTF8.GetBytes($"Уравнение имеет два корня: {FormatRoot(root1)} и {FormatRoot(root2)}"));
Console.WriteLine($"Уравнение имеет два корня: {FormatRoot(root1)} и {FormatRoot(root2)}");
}
solvedEquationsCount++;
Console.WriteLine($"Решено уравнений: {solvedEquationsCount}");
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static string GenerateClientId()
{
Random random = new Random();
string clientId;
do
{
clientId = random.Next(10000000, 99999999).ToString();
} while (usedClientIds.Contains(clientId));
return clientId;
}
static string FormatRoot(double root)
{
return root == 0 ? "0" : root.ToString();
}
}
client.cs:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect("127.0.0.1", 8888);
Console.WriteLine("Введите коэффициенты a, b и c через пробел:");
string equation = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(equation);
socket.Send(data);
byte[] buffer = new byte[512];
int bytesReceived = socket.Receive(buffer);
string response = Encoding.UTF8.GetString(buffer, 0, bytesReceived);
Console.WriteLine(response);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
}
Выводы о корнях:
Выводы об ошибках:
Download