У меня есть консольное приложение Asynchronoumus server. Теперь моя проблема в том, что через день или несколько дней приложение внезапно зависло. но я попробовал перехватить все методы, которые у меня есть, похоже, что эта ошибка не обрабатывается catch, просмотрев журналы в программе просмотра событий приложения, я обнаружил эту ошибку в день, когда она была разбита.
Application: CopyChimpServer.exe Framework Version: v4.0.30319 Description:
The process was terminated due to an unhandled exception. Exception Info:
System.Net.Sockets.SocketException at System.Net.Sockets.Socket.BeginReceive(Byte[], Int32, Int32, System.Net.Sockets.SocketFlags,
System.AsyncCallback, System.Object) at CopyChimpServer.Program+<>c__DisplayClass2.<AcceptCallback>b__0()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()
Мой код
private static void ReceiveCallBack(IAsyncResult AR)
{
Thread.Sleep(1000);
Socket socket = null;
string hostname = "";
string ip_address = "";
CopyChimpDB copychimp_db = new CopyChimpDB();
try
{
socket = (Socket)AR.AsyncState;
int received = socket.EndReceive(AR);
ip_address = (socket.RemoteEndPoint as IPEndPoint).ToString().Split(':')[0];
hostname = dict_host[ip_address];
byte[] dataBuff = new byte[received];
Array.Copy(_buffer, dataBuff, received);
string message_to_client = "wait";
if (Convert.ToDouble(Math.Round((DateTime.Now - Convert.ToDateTime(dict_cmd_lastsent[hostname])).TotalMinutes, 2)) >= dict_cmd_interval[hostname])
{
var server_command = ServerCommand(hostname);
if (server_command.Trim() != "")
{
//string message_from_client = WebUtility.HtmlDecode(Encoding.ASCII.GetString(dataBuff));
message_to_client += "<DriveName>" + dict_drive[hostname] + "</DriveName>";
message_to_client += "<ServerCommand>" + ServerCommand(hostname) + "</ServerCommand>";
try
{
copychimp_db.PostCopyChimp("ConnectMachine", hostname, ip_address);
}
catch (Exception oraex)
{
ServerLogs(hostname + "--" + oraex.ToString());
}
dict_cmd_lastsent[hostname] = DateTime.Now;
//ServerLogs(hostname + " updated");
}
}
byte[] data = Encoding.ASCII.GetBytes(message_to_client);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
}
catch (SocketException ex)
{
try
{
//_clientSockets.Remove(socket);
ServerLogs(hostname + " SocketException! " + ex.Message.ToString());
if (hostname != "")
{
try
{
copychimp_db.PostCopyChimp("DisconnectMachine", hostname, ip_address);
}
catch (Exception oraex)
{
ServerLogs(hostname + "--" + oraex.ToString());
}
}
}
catch (Exception ex_)
{
ServerLogs(hostname + " DisconnectMachine error! " + ex_.ToString());
}
}
}
private static void AcceptCallback(IAsyncResult AR)
{
string hostname = "";
try
{
CopyChimpDB copychimp_db = new CopyChimpDB();
Socket socket = _serverSocket.EndAccept(AR);
string ip_address = "";
//hostname checking
ip_address = (socket.RemoteEndPoint as IPEndPoint).ToString().Split(':')[0];
try
{
try
{
hostname = Dns.GetHostEntry(ip_address).HostName;
}
catch (Exception host_ex)
{
ServerLogs(ip_address + " GetHostEntry error: " + host_ex.Message.ToString());
DataTable dt_ip = copychimp_db.GetCopyChimp("GetHostnameByIpAddress", hostname, ip_address);
if (dt_ip.Rows.Count == 1)
{
hostname = dt_ip.Rows[0]["hostname"].ToString();
ServerLogs(ip_address + " GetHostnameByIpAddress : " + hostname);
}
}
DataTable dt_hostname = copychimp_db.GetCopyChimp("GetHostname", hostname, ip_address);
hostname = "";
if (dt_hostname.Rows.Count == 1)
{
hostname = dt_hostname.Rows[0]["hostname"].ToString();
}
else if (dt_hostname.Rows.Count > 1)
{
ServerLogs(hostname + " GetHostname error: Returns more than 1 row.");
}
if (hostname != "")
{
if (!_clientSockets.Contains(socket))
{
dict_host[ip_address] = hostname;
_clientSockets.Add(socket);
copychimp_db.PostCopyChimp("ConnectMachine", hostname, ip_address);
/*------------------------------------------------------------------------------------------------*/
dict_cmd_interval[hostname] = Convert.ToDouble(copychimp_db.GetCopyChimp("GetInterval", hostname, ip_address).Rows[0]["interval"].ToString());
/*------------------------------------------------------------------------------------------------*/
dict_cmd_lastsent[hostname] = Convert.ToDateTime(copychimp_db.GetCopyChimp("GetLastUpdate", hostname, ip_address).Rows[0]["lastupdate"]);
/*------------------------------------------------------------------------------------------------*/
dict_drive[hostname] = copychimp_db.GetCopyChimp("GetDriveName", hostname, ip_address).Rows[0]["drive_name"].ToString();
/*------------------------------------------------------------------------------------------------*/
thread = new Thread(() =>
{
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
});
thread.Start();
ServerLogs(hostname + " connected");
}
}
}
catch (Exception oraex)
{
ServerLogs(hostname + "--" + oraex.ToString());
}
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch (SocketException ex)
{
ServerLogs("AcceptCallback SocketException " + hostname + ex.Message.ToString());
}
}
Есть ли способ избежать этой ошибки или перехватить эту ошибку? Будет ли отдельный ответ поймать на BeginReceive будет ответ?