public Client(ListenerContext ctx, Socket clientSocket) { Context = ctx; Id = ctx.IdCounter++; _socket = clientSocket; _server = Context.ServerFactory.CreateServer(); _server.Client = this; OnClientExit += c => _server.OnStop(); }
private void StartAccept(ListenerContext ctx, bool inAcceptCallback) { if (ctx.MaxConnections <= 0) { if (!inAcceptCallback) { return; } try { Debug.WriteLine("BeginAccept"); ctx.ListenSocket.BeginAccept(AcceptCallback, ctx); } catch (ObjectDisposedException) { // Ignore } } else { lock (ctx.SyncRoot) { Debug.WriteLine($"inAcceptCallback = {inAcceptCallback} Accepting = {ctx.Accepting} Client count = {ctx.Clients.Count}"); if (ctx.Accepting || ctx.Clients.Count >= ctx.MaxConnections) { return; } try { Debug.WriteLine("BeginAccept"); if (!ctx.ListenSocket.BeginAccept(AcceptCallbackLimited, ctx).CompletedSynchronously) { ctx.Accepting = true; } } catch (ObjectDisposedException) { // Ignore } } } }
public void Start() { var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); var endPoint = new IPEndPoint(IPAddress.Loopback, Port); listenSocket.Bind(endPoint); listenSocket.Listen(1024); var serverFactory = ServerFactory; if (serverFactory == null) { throw new Exception("ServerFactory must be set before Sstart()!"); } var context = new ListenerContext(listenSocket, MaxConnections, serverFactory); if (Interlocked.CompareExchange(ref _currentContext, context, null) == null) { StartAccept(context, true); } else { throw new Exception("Already started!"); } } catch (Exception) { listenSocket.Close(); throw; } }