public class ServerSocket
{
private int Port;
private Socket Sock;
private BruteforceProtection protection;
public Action<SocketWrapper> OnConnect, OnDisconnect;
public Action<SocketWrapper, byte[]> OnReceive;
public ServerSocket(int Port)
{
this.Port = Port;
protection = new BruteforceProtection();
Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Sock.Bind(new IPEndPoint(IPAddress.Any, Port));
Sock.NoDelay = true;
Sock.Listen(0);
Sock.BeginAccept(new AsyncCallback(AcceptCallBack), null);
Console.WriteLine($"Accepting on port {Port}");
}
private void AcceptCallBack(IAsyncResult ar)
{
try
{
Socket acceptor = Sock.EndAccept(ar);
string IP = (acceptor.RemoteEndPoint as IPEndPoint).Address.ToString();
if (protection.CanLogin(IP))
{
SocketWrapper wrapper = new SocketWrapper(this, acceptor);
InvokeConnected(wrapper);
wrapper.TryReceive();
}
else
acceptor.Disconnect(false);
}
catch (Exception e)
{
Loggers.LoggersController.LogException(e.ToString());
}
finally
{
// Sock.BeginAccept(new AsyncCallback(AcceptCallBack), null);
Sock.BeginAccept(new AsyncCallback(AcceptCallBack), acceptor);
}
}
public void InvokeConnected(SocketWrapper wrapper)
{
if (OnConnect != null)
OnConnect.Invoke(wrapper);
}
public void InvokeReceive(SocketWrapper wrapper, byte[] buffer)
{
if (OnReceive != null)
OnReceive.Invoke(wrapper, buffer);
}
public void InvokeDisconnect(SocketWrapper wrapper)
{
if (OnDisconnect != null)
OnDisconnect.Invoke(wrapper);
}
}
this is my code. The line Socket acceptor = Sock.EndAccept(ar);
is throwing:
System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
It usually happens in an hour, can happen in 10 minutes or 59 minutes but definitely does happen. I tried to change finally block from null to connect to acceptor again as I saw this approach on somewhere but still getting this exception. Can anyone see what's wrong with it?
User contributions licensed under CC BY-SA 3.0