PuTTY отправляет пустые сообщения, вызывая проблемы со связью TCP-сервераC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 PuTTY отправляет пустые сообщения, вызывая проблемы со связью TCP-сервера

Сообщение Anonymous »

Я столкнулся с проблемой PuTTY: он отправляет пустые сообщения на мой TCP-сервер, что приводит к сбоям в связи. Я создаю приложение TCP-сервера на C#, которое взаимодействует с клиентами, включая PuTTY в качестве одного из клиентов. Сервер предназначен для обработки команд, отправленных клиентами, выполнения соответствующих действий и ответа. Сервер и клиент работают правильно.
Проблема возникает, когда PuTTY(Raw) отправляет на сервер пустые сообщения. Получено от клиента = Recebido do cliente

Код: Выделить всё

using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class Server
{
private const string clientesServicosPath = "C:\\Project\\Database\\AllocationFile.csv";
private const string servicoPath = "C:\\Project\\Database";
private static readonly Mutex mutex = new Mutex();

static void Main(string[] args)
{
IPAddress ip = IPAddress.Any;
TcpListener listener = new TcpListener(ip, 8080);
listener.Start();
Console.WriteLine("Servidor iniciado.  Aguardando conexões...");

try
{
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Thread clientThread = new Thread(HandleClient);
clientThread.Start(client);
}
}
finally
{
listener.Stop();
}
}

private static void HandleClient(object clientObj)
{
TcpClient client = (TcpClient)clientObj;
NetworkStream stream = client.GetStream();
string clientId = null;

try
{
while (true)
{
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string request = Encoding.ASCII.GetString(buffer, 0, bytesRead).Trim();

Console.WriteLine($"Recebido do cliente: {request}");
if (request.StartsWith("ID"))
{
clientId = request.Split(' ')[1];
Console.WriteLine($"Cliente {clientId} conectado.");
continue;
}

string response = "";
if (request.Equals("QUIT"))
{
response = "400 BYE";
byte[] responseBytes = Encoding.ASCII.GetBytes(response + Environment.NewLine);
stream.Write(responseBytes, 0, responseBytes.Length);
Console.WriteLine($"Resposta para o cliente: {response}");
break;
}
else if (request.StartsWith("TASK_COMPLETE"))
{
string taskId = request.Split(' ')[1];
MarkTaskAsCompleted(taskId, clientId);
response = "Tarefa marcada como concluida.";
Console.WriteLine($"Resposta para o cliente: {response}");
}
else if (request.Equals("REQUEST_TASK"))
{
string taskDetails = AllocateTask(clientId);
response = taskDetails ?? "Nenhuma tarefa disponivel.";
Console.WriteLine($"Resposta para o cliente: {response}");
}
else if (request.Equals("SHOW_TASK"))
{
response = ShowTask(clientId);
Console.WriteLine($"Resposta para o cliente: {response}");
}

byte[] msgBytes = Encoding.ASCII.GetBytes(response + Environment.NewLine);
stream.Write(msgBytes, 0, msgBytes.Length);
}
}
catch (Exception e)
{
Console.WriteLine($"Uma excecao ocorreu: {e.Message}");
}
finally
{
client.Close();
}
}
private static void MarkTaskAsCompleted(string taskId, string clientId)
{
try
{
mutex.WaitOne(); // Aguarda a aquisição do mutex

// Encontre o serviço associado ao cliente
string serviceId = FindClientService(clientId);
if (serviceId == null)
{
Console.WriteLine("Nenhum servico alocado a este cliente.");
return;
}

// Construa o caminho do arquivo de tarefas do serviço específico
string taskFilePath = Path.Combine("C:\\Project\\Database", $"{serviceId}.csv");

// Verifique se o arquivo existe
if (!File.Exists(taskFilePath))
{
Console.WriteLine($"Ficheiro de tarefa nao encontrado: {taskFilePath}");
return;
}

// Carregar as linhas do arquivo de tarefas
string[] lines = File.ReadAllLines(taskFilePath);

// Procurar pela tarefa em curso com o ID correto
for (int i = 1; i < lines.Length; i++) // Suponha que haja um cabeçalho
{
string[] parts = lines[i].Split(',');
if (parts.Length >= 3 && parts[0] == taskId &&  parts[2].Trim() == "Em_curso")
{
// Marcar a tarefa como concluída
parts[2] = "Concluido";
lines[i] = string.Join(",", parts);

// Salvar as alterações no arquivo
File.WriteAllLines(taskFilePath, lines);
Console.WriteLine($"Tarefa {taskId} marcada como completa para o cliente {clientId}.");
return;
}
}

Console.WriteLine($"A tarefa {taskId} nao foi encontrada ou nao esta em curso para o cliente {clientId}.");
}
catch (Exception ex)
{
Console.WriteLine($"Um erro ocorreu a mostrar a tarefa como concluida: {ex.Message}");
}
finally
{
mutex.ReleaseMutex(); // Libera o mutex após a operação
}
}

private static string FindClientService(string clientId)
{
mutex.WaitOne(); // Aguarda a aquisição do mutex

try
{
// Assume-se que o arquivo contém um cabeçalho
string[] lines = File.ReadAllLines(clientesServicosPath);
foreach (string line in lines.Skip(1)) // Pula o cabeçalho
{
string[] parts = line.Split(',');
if (parts[0].Trim().Equals(clientId, StringComparison.OrdinalIgnoreCase))
{
// Retorna o ID do serviço associado ao cliente
return parts[1].Trim();
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao aceder ao ficheiro {clientesServicosPath}: {ex.Message}");
}
finally
{
mutex.ReleaseMutex(); // Libera o mutex após a operação
}

// Retorna null se não encontrar o serviço ou se ocorrer um erro
return null;
}

private static string AllocateTask(string clientId)
{
mutex.WaitOne(); // Aguarda a aquisição do mutex

try
{
// Primeiro, encontre o serviço associado ao cliente
string serviceId = FindClientService(clientId);
if (string.IsNullOrEmpty(serviceId))
{
return "Nenhum servico alocado a este cliente.";
}

// Construa o caminho para o arquivo de serviço específico usando serviceId
string taskFilePath = Path.Combine("...", $"{serviceId}.csv");

// Verificar se o arquivo existe
if (!File.Exists(taskFilePath))
{
return "Ficheiro de tarefa nao encontrado.";
}

// Carregar as linhas do arquivo de tarefas do serviço específico
var lines = File.ReadAllLines(taskFilePath).ToList();

// Procurar pela primeira tarefa não alocada
for (int i = 1; i < lines.Count; i++) // Suponha que haja um cabeçalho
{
var parts = lines[i].Split(',');
if (parts.Length >= 4 && parts[2].Trim() == "Nao_alocado") // Verifica se há elementos suficientes
{
parts[2] = "Em_curso"; // Atualiza o status para em progresso
parts[3] = clientId;   // Atribui a tarefa ao cliente
lines[i] = string.Join(",", parts);

// Salvar as alterações de volta ao arquivo CSV
File.WriteAllLines(taskFilePath, lines);

// Retorna detalhes da tarefa alocada
return $"Tarefa {parts[0]} alocada ao cliente {clientId}.";
}
}

return "Nenhuma tarefa disponível.";
}
finally
{
mutex.ReleaseMutex(); // Libera o mutex após a operação
}
}

private static string ShowTask(string clientId)
{

mutex.WaitOne();  // Aguarda a aquisição do mutex

try
{
string serviceId = FindClientService(clientId);
if (serviceId == null)
{
return "Nenhum servico alocado a este cliente.";
}

string taskFilePath = Path.Combine(servicoPath, $"{serviceId}.csv");

if (!File.Exists(taskFilePath))
{
return "Ficheiro de tarefa nao encontrado.";
}

string[] lines = File.ReadAllLines(taskFilePath);

// Procurar por tarefas em curso para o cliente
StringBuilder taskDetails = new StringBuilder();
bool found = false;
foreach (string line in lines.Skip(1)) // Pular o cabeçalho
{
string[] parts = line.Split(',');
if (parts.Length >= 4 && parts[2].Trim() == "Em_curso" && parts[3].Trim() == clientId)
{
taskDetails.AppendLine($"Servico: {serviceId};\nTarefa: {parts[0]};\nDescricao: {parts[1]};\nEstado: Em curso;");
found = true;
}
}

if (!found)
{
return "Nenhuma tarefa alocada a este cliente.";
}

return taskDetails.ToString();
}

catch (Exception ex)
{
Console.WriteLine($"Um erro ocorreu a mostrar as tarefas: {ex.Message}");
return "Error showing tasks.";
}
finally
{
mutex.ReleaseMutex(); // Libera o mutex após a operação
}

}

}
Ппробованные решения
Я пытался заставить его игнорировать сообщения, но это не сработало.

Код: Выделить всё

private static void HandleClient(object clientObj)
{
TcpClient client = (TcpClient)clientObj;
NetworkStream stream = client.GetStream();
string clientId = null;

try
{
while (true)
{
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
// Cliente desconectado
break;
}

string request = Encoding.ASCII.GetString(buffer, 0, bytesRead).Trim();

if (string.IsNullOrEmpty(request))
{
// Ignorar mensagens vazias
continue;
}

Console.WriteLine($"Recebido do cliente: {request}");

if (request.StartsWith("ID"))
{
clientId = request.Split(' ')[1];
Console.WriteLine($"Cliente {clientId} conectado.");
continue;
}
P.S. Я не использую Telnet и SSH в PuTTY

Подробнее здесь: https://stackoverflow.com/questions/783 ... munication
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»