The remote host forcibly terminated an existing connection
I get this error. The connection is made using this code. When I reduce the time, the program goes, but still writes that there are 0 messages in the mail, although they are there.
/// <summary>
/// Считывает первую строку ответа сервера из буфера
/// </summary>
public string ReadLine()
{
byte[] b = new byte[this._Socket.ReceiveBufferSize];
StringBuilder result = new StringBuilder(this._Socket.ReceiveBufferSize);
int s = 0;
// если будут проблемы с Poll, увеличьте время с 1000000 мс до ...
while (this._Socket.Poll(1000000, SelectMode.SelectRead) && (s = this._Socket.Receive(b, this._Socket.ReceiveBufferSize, SocketFlags.None)) > 0)
{
result.Append(System.Text.Encoding.ASCII.GetChars(b, 0, s));
}
this.WriteToLog(result.ToString().TrimEnd("\r\n".ToCharArray()));// логирование
return result.ToString().TrimEnd("\r\n".ToCharArray());
}
Here is the main code of the Client file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace Кассовый_чек
{
public class Client
{
private Socket _Socket = null;
private string _Host = String.Empty;
private int _Port = 110;
private string _UserName = String.Empty;
private string _Password = String.Empty;
private Result _ServerResponse = new Result();
private int _Index = 0;
public int MessageCount = 0;
public int MessagesSize = 0;
public Client(string host, string userName, string password)
: this(host, 110, userName, password)
{
}
public Client(string host, int port, string userName, string password)
{
// проверка указания всех необходимых данных
if (String.IsNullOrEmpty(host)) throw new Exception("Необходимо указать адрес pop3-сервера.");
if (String.IsNullOrEmpty(userName)) throw new Exception("Необходимо указать логин пользователя.");
if (String.IsNullOrEmpty(password)) throw new Exception("Необходимо указать пароль пользователя.");
if (port <= 0) port = 110;
//--
this._Host = host;
this._Password = password;
this._Port = port;
this._UserName = userName;
}
public int Port {
get => this._Port;
set => this._Port = value;
}
/// <summary>
/// Метод осуществляет подключение к почтовому серверу
/// </summary>
public void Connect()
{
// получаем апишник сервера
IPHostEntry myIPHostEntry = Dns.GetHostEntry(this._Host);
if (myIPHostEntry == null || myIPHostEntry.AddressList == null || myIPHostEntry.AddressList.Length <= 0)
{
throw new Exception("Не удалось определить IP-адрес по хосту.");
}
// получаем сетевую конечную точку
IPEndPoint myIPEndPoint = new IPEndPoint(myIPHostEntry.AddressList[0], this._Port);
// инициализируем сокет
this._Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this._Socket.ReceiveBufferSize = 512; // размер приемного буфера в байтах
// соединяемся с сервером
this.WriteToLog("Соединяюсь с сервером {0}:{1}", this._Host, this._Port);
this._Socket.Connect(myIPEndPoint);
// получаем ответ сервера
this.ReadLine();
// выполняем авторизацию
this.Command(String.Format("USER {0}", this._UserName));
this.ReadLine();
this.Command(String.Format("PASS {0}", this._Password));
// сервер обычно проводит окончательную проверку
// только после указания пароля,
// так что проверять ответ на ошибки до этого момента
// смысла нет
this._ServerResponse = this.ReadLine();
if (this._ServerResponse.IsError)
{
throw new Exception(this._ServerResponse.ServerMessage);
}
// запрашиваем статистику почтового ящика
this.Command("STAT");
this._ServerResponse = this.ReadLine();
if (this._ServerResponse.IsError)
{
throw new Exception(this._ServerResponse.ServerMessage);
}
this._ServerResponse.ParseStat(out this.MessageCount, out this.MessagesSize);
}
/// <summary>
/// Метод завершает сеанс связи с сервером
/// </summary>
public void Close()
{
if (this._Socket == null) { return; }
this.Command("QUIT");
this.ReadLine();
this._Socket.Close();
}
/// <summary>
/// Фукнция возвращает заголовки указанного письма
/// </summary>
/// <param name="index">Индекс письма, начиная с 1</param>
public Dictionary<string, object> GetMailHeaders(int index)
{
if (index > this.MessageCount)
{
throw new Exception(String.Format("Индекс должен быть от 1 и не больше {0}", this.MessageCount));
}
this.Command(String.Format("TOP {0} 0", index));
this._ServerResponse = this.ReadToEnd();
if (this._ServerResponse.IsError)
{
throw new Exception(this._ServerResponse.ServerMessage);
}
MailItem m;
this._ServerResponse.ParseMail(out m);
return m.Headers;
}
/// <summary>
/// Следующее письмо
/// </summary>
public bool NextMail(out MailItem m)
{
m = null;
// следующее письмо
this._Index++;
// если больше писем нет, возвращаем false
if (this._Index > this.MessageCount) return false;
this.Command(String.Format("RETR {0}", this._Index));
this._ServerResponse = this.ReadToEnd();
if (this._ServerResponse.IsError)
{
throw new Exception(this._ServerResponse.ServerMessage);
}
this._ServerResponse.ParseMail(out m);
return true;
}
/// <summary>
/// Метод удаляет текущее письмо
/// </summary>
public void Delete()
{
this.Delete(this._Index);
}
/// <summary>
/// Метод удаляет указанное письмо
/// </summary>
public void Delete(int index)
{
if (index > this.MessageCount)
{
throw new Exception(String.Format("Индекс должен быть от 1 и не больше {0}", this.MessageCount));
}
this.Command(String.Format("DELE {0}", index));
this._ServerResponse = this.ReadLine();
if (this._ServerResponse.IsError)
{
throw new Exception(this._ServerResponse.ServerMessage);
}
}
/// <summary>
/// Метод отправляет команду почтовому серверу
/// </summary>
/// <param name="cmd">Команда</param>
public void Command(string cmd)
{
if (this._Socket == null) throw new Exception("Соединение с сервером не установлено. Откройте соединение методом Connect.");
this.WriteToLog("Команда: {0}", cmd);// логирование
byte[] b = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", cmd));
if (this._Socket.Send(b, b.Length, SocketFlags.None) != b.Length)
{
throw new Exception("При отправке данных удаленному серверу произошла ошибка...");
}
}
/// <summary>
/// Считывает первую строку ответа сервера из буфера
/// </summary>
public string ReadLine()
{
byte[] b = new byte[this._Socket.ReceiveBufferSize];
StringBuilder result = new StringBuilder(this._Socket.ReceiveBufferSize);
int s = 0;
// если будут проблемы с Poll, увеличьте время с 1000000 мс до ...
while (this._Socket.Poll(1000000, SelectMode.SelectRead) && (s = this._Socket.Receive(b, this._Socket.ReceiveBufferSize, SocketFlags.None)) > 0)
{
result.Append(System.Text.Encoding.ASCII.GetChars(b, 0, s));
}
this.WriteToLog(result.ToString().TrimEnd("\r\n".ToCharArray()));// логирование
return result.ToString().TrimEnd("\r\n".ToCharArray());
}
/// <summary>
/// Читает и возвращает все содержимое ответа сервера из буфера
/// </summary>
public string ReadToEnd()
{
byte[] b = new byte[this._Socket.ReceiveBufferSize];
StringBuilder result = new StringBuilder(this._Socket.ReceiveBufferSize);
int s = 0;
// если будут проблемы с Poll, увеличьте время с 1000000 мс до ...
while (this._Socket.Poll(1000000, SelectMode.SelectRead) && ((s = this._Socket.Receive(b, this._Socket.ReceiveBufferSize, SocketFlags.None)) > 0))
{
result.Append(System.Text.Encoding.ASCII.GetChars(b, 0, s));
}
// логирование
if (result.Length > 0 && result.ToString().IndexOf("\r\n") != -1)
{
this.WriteToLog(result.ToString().Substring(0, result.ToString().IndexOf("\r\n")));
}
// --
return result.ToString();
}
private void WriteToLog(string msg, params object[] args)
{
Console.WriteLine("{0}: {1}", DateTime.Now, String.Format(msg, args));
}
}
}
And this code already displays everything on the screen
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;
using System.IO;
namespace Кассовый_чек
{
class Program
{
static void Main(string[] args)
{
/*
* ВНИМАНИЕ. НЕ ЗАБУДЬТЕ УКАЗАТЬ АДРЕС ПОЧТОВОГО СЕРВЕРА, СУЩЕСТВУЮЩИЕ ИМЯ ПОЛЬЗОВАТЕЛЯ И ПАРОЛЬ!
*/
Client check;
using (var setingsReader = new StreamReader(new FileStream("settings.ini", FileMode.OpenOrCreate)))
{
var host = setingsReader.ReadLine();
var login = setingsReader.ReadLine();
var password = setingsReader.ReadLine();
check = new Client(host, 995, login, password);
}
check.Connect();
Console.WriteLine($"количество сообщений: {check.MessageCount}");
Кассовый_чек.MailItem m;
while (check.NextMail(out m))
{
Console.Write("Письмо от {0} с темой {1}", m.From, m.Subject);
Console.WriteLine("Хотите его удалить (y/n)?");
if (Console.ReadLine().ToLower().StartsWith("y"))
{
// ставим текущему письму отметку об удалении
check.Delete();
Console.WriteLine("Письмо помечено для удаления.");
}
}
check.Close();
Console.ReadLine();
Console.ReadKey();
}
}
}
HELP ME, WHAT IS MY MISTAKE?
THIS IS WHERE THE PROJECT IS LOCATED IF SOMEONE LOOKS AT MY PROGRAM, MAYBE THEY WILL UNDERSTAND WHAT THE ERROR IS, HERE LINK: https://yadi.sk/d/oB13KErH1WUWrw
0
Author: HolyBlackCat, 2020-04-21