Я столкнулся с проблемой 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
}
}
}
Ппробованные решения
Я пытался заставить его игнорировать сообщения, но это не сработало.
Я столкнулся с проблемой PuTTY: он отправляет пустые сообщения на мой TCP-сервер, что приводит к сбоям в связи. Я создаю приложение TCP-сервера на C#, которое взаимодействует с клиентами, включая PuTTY в качестве одного из клиентов. Сервер предназначен для обработки команд, отправленных клиентами, выполнения соответствующих действий и ответа. Сервер и клиент работают правильно. Проблема возникает, когда PuTTY(Raw) отправляет на сервер пустые сообщения. Получено от клиента = Recebido do cliente [code]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...");
// 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."; }
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 }
}
} [/code] Ппробованные решения Я пытался заставить его игнорировать сообщения, но это не сработало. [code]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; }
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; } [/code] P.S. Я не использую Telnet и SSH в PuTTY
У меня есть вариант использования, когда мне нужно отправлять сообщения на внешний TCP-сервер с 2 IP/портами для кругового распределения (каждое соединение для каждой пары IP/портов, и оно должно поддерживаться для обмена сообщениями). ).
Я...
Приведенный ниже скрипт отправит электронное письмо после отправки формы, но имя от имени — $name, строка темы верна, электронное письмо отправляется на правильный адрес электронной почты, ответ — $name, а сообщения электронной почты — это точное...
Я пытаюсь войти на свой VPS-сервер (платный сторонний хостинг) через Putty как root, но putty возвращает: «сервер отказался от нашего ключа» и отображает всплывающее окно с сообщением:
Нет поддерживаемых методов аутентификации ( сервер отправил:...
Когда я вхожу в систему Kodi с помощью Putty, я не могу прочитать имена некоторых системных файлов из-за цвета. Я не уверен, является ли это проблемой Linux или проблемой Putty. Некоторые имена файлов/папок легко прочитать, но некоторые мне кажутся...
поэтому я вносил некоторые изменения в разрешения для нового пользователя, и мне не нужно было иметь доступ ни к чему, кроме его дома и папки внутри папки /var/www, поэтому я изменил разрешения на /var и /etc с помощью chmod и chwon, и этот сайт...