64 lines
2.6 KiB
C#
64 lines
2.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net.Sockets;
|
|
using System.Net;
|
|
|
|
using BCG;
|
|
|
|
namespace bts {
|
|
// TODO: replace it with AsyncTCPConnectionAcceptor_APM
|
|
public class ServerToClientManagedTCPConnectionAcceptor {
|
|
|
|
private readonly int _port;
|
|
private readonly ITCPConnectionHandler _handler;
|
|
private readonly Socket _accept_socket;
|
|
public ServerToClientManagedTCPConnectionAcceptor(int port, ITCPConnectionHandler handler) {
|
|
bts.Log.Gen.info($"ServerToClientManagedTCPConnectionAcceptor.cons port: {port}");
|
|
_port = port;
|
|
_handler = handler;
|
|
_accept_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
|
Func<bool> bind = () => {
|
|
try {
|
|
_accept_socket.Bind(new IPEndPoint(IPAddress.Any, port));
|
|
_accept_socket.Listen(250);
|
|
return true;
|
|
} catch (Exception ex) {
|
|
Log.Gen.error($"ServerToClientManagedTCPConnectionAcceptor.cons bind on port: {port} exception: {ex}");
|
|
return false;
|
|
}
|
|
};
|
|
bts.Log.assert(bind());
|
|
Log.Gen.info($"ServerToClientManagedTCPConnectionAcceptor.cons bind to port: {port} successful");
|
|
}
|
|
|
|
public void activate() {
|
|
bts.Log.Gen.info($"ServerToClientManagedTCPConnectionAcceptor.activate called port: {_port}");
|
|
_accept_socket.BeginAccept(new AsyncCallback(_on_accept), new object[] { });
|
|
}
|
|
|
|
private void _on_accept(IAsyncResult res) {
|
|
Log.Gen.info($"ServerToClientManagedTCPConnectionAcceptor._on_accept called port: {_port}");
|
|
Socket new_sock;
|
|
try {
|
|
new_sock = _accept_socket.EndAccept(res);
|
|
} catch (Exception ex) {
|
|
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
|
|
_accept_socket.BeginAccept(new AsyncCallback(_on_accept), new object[] { });
|
|
if (ex is OutOfMemoryException)
|
|
throw ex;
|
|
return;
|
|
}
|
|
new_sock.LingerState = new LingerOption(false, 0);
|
|
new_sock.Blocking = false;
|
|
ITCPConnection new_conn = new bts.AsyncTCPConnection_APM(new_sock, TimeSpan.FromSeconds(1), ITCPConnection.ConnectionSide.Server);
|
|
_handler.onConnection(new_conn);
|
|
_accept_socket.BeginAccept(new AsyncCallback(_on_accept), new object[] { });
|
|
var peer_rci = new_conn.get_peer_address();
|
|
Log.Gen.info($"ServerToClientManagedTCPConnectionAcceptor._on_accept connection accepted successfully from rci: {peer_rci}");
|
|
}
|
|
}
|
|
|
|
|
|
}
|