Programming Search⌘K

Patternadvanced

Acceptor-Connector

Also called acceptor connector, acceptor-connector pattern, acceptor and connector.

Acceptor-Connector puts the code that sets up a connection in an acceptor or a connector, and the code that uses the connection in a service handler.

Family
concurrency
Intent
Decouple the passive and the active set-up of connections, and the start of the service on them, from the processing that the service does after the connection is set up.

Intent

The Acceptor-Connector design pattern decouples connection establishment and service initialization in a distributed system from the processing performed once a service is initialized.1 This decoupling is achieved with three components: acceptors, connectors, and service handlers.1

Problem

A program in a network both waits for connections and starts them. The code that listens, connects and builds the objects for a new connection is much the same in each program. The code that runs on the connection is different for each service. When both are in one function, a new service needs a copy of the set-up code, and a change to the set-up code touches each service.

Solution

There are three roles.1

  • Acceptor. An Acceptor is a factory that implements the strategy for passively establishing a connection and initializing its associated Service Handler.1
  • Connector. A Connector is a factory that implements the strategy for actively establishing a connection and initializing its associated Service Handler.1 It provides another method that finishes activating Service Handlers whose connections were initiated either synchronously or asynchronously.1
  • Service Handler. A Service Handler implements an application service, typically playing the client role, server role, or both roles.1 It provides a hook method that is called by an Acceptor or Connector to activate the application service when the connection is established.1
 passive side                         active side
 Acceptor(addr, make_handler)         Connector.connect(addr, make_handler)
   listen(addr)  <------- connect --------+
   accept(): h = make_handler()           | complete(): h = make_handler()
             h.open(conn)                 |             h.open(conn)
                    \                    /
                 Service Handler <--> Service Handler
                      (application protocol only)

A dispatcher, such as a Reactor, tells the acceptor when a connection arrives and the connector when a connection completes.1

Example

The example files show one program in each language. A table of listeners stands in for the network. The acceptor listens on an address and makes a status handler for each connection. The connector connects to that address and makes a command handler. After the set-up, only the two handlers talk. The program prints:

listen gateway:9000
connect gateway:9000
accept -> status handler open
connect done -> command handler open
command: send reset
status: got reset
PythonGitHub
class Channel:
    def __init__(self):
        self.messages = []


class StatusHandler:  # service handler on the passive side
    def open(self, channel):
        self.channel = channel
        print("accept -> status handler open")

    def poll(self):
        print("status: got", self.channel.messages.pop(0))


class CommandHandler:  # service handler on the active side
    def open(self, channel):
        self.channel = channel
        print("connect done -> command handler open")

    def send(self, text):
        print("command: send", text)
        self.channel.messages.append(text)


listeners = {}  # stands in for the network


class Acceptor:
    def __init__(self, address, make_handler):
        self.make_handler = make_handler
        self.handlers = []
        listeners[address] = self
        print("listen", address)

    def accept(self, channel):
        handler = self.make_handler()
        handler.open(channel)
        self.handlers.append(handler)


class Connector:
    def connect(self, address, make_handler):
        print("connect", address)
        channel = Channel()
        listeners[address].accept(channel)
        return self.complete(channel, make_handler)

    def complete(self, channel, make_handler):
        handler = make_handler()
        handler.open(channel)  # activate only when the connection is up
        return handler


acceptor = Acceptor("gateway:9000", StatusHandler)
command = Connector().connect("gateway:9000", CommandHandler)
command.send("reset")
acceptor.handlers[0].poll()
Output
listen gateway:9000
connect gateway:9000
accept -> status handler open
connect done -> command handler open
command: send reset
status: got reset
  • Verdict: idiom. A class is a factory, so the acceptor and the connector take the handler class itself and call it to make each handler.
#include <deque>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>

using Channel = std::shared_ptr<std::deque<std::string>>;

struct StatusHandler {
    Channel channel;
    void open(Channel c) { channel = c; std::cout << "accept -> status handler open\n"; }
    void poll() { std::cout << "status: got " << channel->front() << "\n"; channel->pop_front(); }
};

struct CommandHandler {
    Channel channel;
    void open(Channel c) { channel = c; std::cout << "connect done -> command handler open\n"; }
    void send(const std::string& text) {
        std::cout << "command: send " << text << "\n";
        channel->push_back(text);
    }
};

struct AcceptorBase {
    virtual ~AcceptorBase() = default;
    virtual void accept(Channel channel) = 0;
};

std::map<std::string, AcceptorBase*> listeners;  // stands in for the network

template <typename Handler>
struct Acceptor : AcceptorBase {
    std::vector<Handler> handlers;
    explicit Acceptor(const std::string& address) {
        listeners[address] = this;
        std::cout << "listen " << address << "\n";
    }
    void accept(Channel channel) override {
        Handler handler;
        handler.open(channel);
        handlers.push_back(handler);
    }
};

template <typename Handler>
Handler connect(const std::string& address) {
    std::cout << "connect " << address << "\n";
    auto channel = std::make_shared<std::deque<std::string>>();
    listeners.at(address)->accept(channel);
    Handler handler;  // complete: activate when the connection is up
    handler.open(channel);
    return handler;
}

int main() {
    Acceptor<StatusHandler> acceptor("gateway:9000");
    auto command = connect<CommandHandler>("gateway:9000");
    command.send("reset");
    acceptor.handlers[0].poll();
}
Output
listen gateway:9000
connect gateway:9000
accept -> status handler open
connect done -> command handler open
command: send reset
status: got reset
  • Verdict: idiom. The acceptor and the connector are templates over the handler type, as in the paper's C++ code.
JavaGitHub
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

public class Main {
    interface ServiceHandler { void open(LinkedList<String> channel); }

    static class StatusHandler implements ServiceHandler {
        LinkedList<String> channel;
        public void open(LinkedList<String> channel) {
            this.channel = channel;
            System.out.println("accept -> status handler open");
        }
        void poll() { System.out.println("status: got " + channel.removeFirst()); }
    }

    static class CommandHandler implements ServiceHandler {
        LinkedList<String> channel;
        public void open(LinkedList<String> channel) {
            this.channel = channel;
            System.out.println("connect done -> command handler open");
        }
        void send(String text) {
            System.out.println("command: send " + text);
            channel.add(text);
        }
    }

    static final Map<String, Acceptor<?>> listeners = new HashMap<>();

    static class Acceptor<H extends ServiceHandler> {
        final List<H> handlers = new ArrayList<>();
        final Supplier<H> make;
        Acceptor(String address, Supplier<H> make) {
            this.make = make;
            listeners.put(address, this);
            System.out.println("listen " + address);
        }
        void accept(LinkedList<String> channel) {
            H handler = make.get();
            handler.open(channel);
            handlers.add(handler);
        }
    }

    static <H extends ServiceHandler> H connect(String address, Supplier<H> make) {
        System.out.println("connect " + address);
        LinkedList<String> channel = new LinkedList<>();
        listeners.get(address).accept(channel);
        H handler = make.get();  // complete: activate when the connection is up
        handler.open(channel);
        return handler;
    }

    public static void main(String[] args) {
        Acceptor<StatusHandler> acceptor = new Acceptor<>("gateway:9000", StatusHandler::new);
        CommandHandler command = connect("gateway:9000", CommandHandler::new);
        command.send("reset");
        acceptor.handlers.get(0).poll();
    }
}
Output
listen gateway:9000
connect gateway:9000
accept -> status handler open
connect done -> command handler open
command: send reset
status: got reset
  • Verdict: idiom. A constructor reference such as StatusHandler::new is the factory that the acceptor calls for each connection.
using System;
using System.Collections.Generic;

interface IServiceHandler { void Open(Queue<string> channel); }

class StatusHandler : IServiceHandler
{
    Queue<string> channel = new();
    public void Open(Queue<string> c) { channel = c; Console.WriteLine("accept -> status handler open"); }
    public void Poll() => Console.WriteLine($"status: got {channel.Dequeue()}");
}

class CommandHandler : IServiceHandler
{
    Queue<string> channel = new();
    public void Open(Queue<string> c) { channel = c; Console.WriteLine("connect done -> command handler open"); }
    public void Send(string text) { Console.WriteLine($"command: send {text}"); channel.Enqueue(text); }
}

interface IAcceptor { void Accept(Queue<string> channel); }

class Acceptor<H> : IAcceptor where H : IServiceHandler, new()
{
    public static readonly Dictionary<string, IAcceptor> Listeners = new();
    public readonly List<H> Handlers = new();
    public Acceptor(string address) { Listeners[address] = this; Console.WriteLine($"listen {address}"); }
    public void Accept(Queue<string> channel) { var h = new H(); h.Open(channel); Handlers.Add(h); }
}

static class Connector
{
    public static H Connect<H>(string address, Dictionary<string, IAcceptor> listeners) where H : IServiceHandler, new()
    {
        Console.WriteLine($"connect {address}");
        var channel = new Queue<string>();
        listeners[address].Accept(channel);
        var handler = new H(); // complete: activate when the connection is up
        handler.Open(channel);
        return handler;
    }
}

static class Program
{
    static void Main()
    {
        var acceptor = new Acceptor<StatusHandler>("gateway:9000");
        var command = Connector.Connect<CommandHandler>("gateway:9000", Acceptor<StatusHandler>.Listeners);
        command.Send("reset");
        acceptor.Handlers[0].Poll();
    }
}
Output
listen gateway:9000
connect gateway:9000
accept -> status handler open
connect done -> command handler open
command: send reset
status: got reset
  • Verdict: idiom. The new() constraint lets the generic acceptor and connector create a handler of the type parameter.
JavaScriptGitHub
class StatusHandler {
  open(channel) {
    this.channel = channel;
    console.log("accept -> status handler open");
  }
  poll() {
    console.log("status: got", this.channel.shift());
  }
}

class CommandHandler {
  open(channel) {
    this.channel = channel;
    console.log("connect done -> command handler open");
  }
  send(text) {
    console.log("command: send", text);
    this.channel.push(text);
  }
}

const listeners = new Map(); // stands in for the network

class Acceptor {
  constructor(address, HandlerClass) {
    this.HandlerClass = HandlerClass;
    this.handlers = [];
    listeners.set(address, this);
    console.log("listen", address);
  }
  accept(channel) {
    const handler = new this.HandlerClass();
    handler.open(channel);
    this.handlers.push(handler);
  }
}

class Connector {
  connect(address, HandlerClass) {
    console.log("connect", address);
    const channel = [];
    listeners.get(address).accept(channel);
    return this.complete(channel, HandlerClass);
  }
  complete(channel, HandlerClass) {
    const handler = new HandlerClass();
    handler.open(channel);
    return handler;
  }
}

const acceptor = new Acceptor("gateway:9000", StatusHandler);
const command = new Connector().connect("gateway:9000", CommandHandler);
command.send("reset");
acceptor.handlers[0].poll();
Output
listen gateway:9000
connect gateway:9000
accept -> status handler open
connect done -> command handler open
command: send reset
status: got reset
  • Verdict: idiom. A class is a value, so the acceptor stores the handler class and calls new on it for each connection.
TypeScriptGitHub
interface ServiceHandler {
  open(channel: string[]): void;
}

class StatusHandler implements ServiceHandler {
  private channel: string[] = [];
  open(channel: string[]): void {
    this.channel = channel;
    console.log("accept -> status handler open");
  }
  poll(): void {
    console.log("status: got", this.channel.shift());
  }
}

class CommandHandler implements ServiceHandler {
  private channel: string[] = [];
  open(channel: string[]): void {
    this.channel = channel;
    console.log("connect done -> command handler open");
  }
  send(text: string): void {
    console.log("command: send", text);
    this.channel.push(text);
  }
}

const listeners = new Map<string, Acceptor<ServiceHandler>>();

class Acceptor<H extends ServiceHandler> {
  readonly handlers: H[] = [];
  private make: () => H;
  constructor(address: string, make: () => H) {
    this.make = make;
    listeners.set(address, this);
    console.log("listen", address);
  }
  accept(channel: string[]): void {
    const handler = this.make();
    handler.open(channel);
    this.handlers.push(handler);
  }
}

class Connector {
  connect<H extends ServiceHandler>(address: string, make: () => H): H {
    console.log("connect", address);
    const channel: string[] = [];
    listeners.get(address)?.accept(channel);
    return this.complete(channel, make);
  }
  private complete<H extends ServiceHandler>(channel: string[], make: () => H): H {
    const handler = make();
    handler.open(channel);
    return handler;
  }
}

const acceptor = new Acceptor("gateway:9000", () => new StatusHandler());
const command = new Connector().connect("gateway:9000", () => new CommandHandler());
command.send("reset");
acceptor.handlers[0].poll();
Output
listen gateway:9000
connect gateway:9000
accept -> status handler open
connect done -> command handler open
command: send reset
status: got reset
  • Verdict: idiom. The acceptor and the connector are generic over the handler type, so connect returns a CommandHandler and the caller can call send without a cast.
package main

import "fmt"

type Channel struct{ messages []string }

type StatusHandler struct{ ch *Channel }

func (h *StatusHandler) Open(ch *Channel) { h.ch = ch; fmt.Println("accept -> status handler open") }
func (h *StatusHandler) Poll() {
	fmt.Println("status: got", h.ch.messages[0])
	h.ch.messages = h.ch.messages[1:]
}

type CommandHandler struct{ ch *Channel }

func (h *CommandHandler) Open(ch *Channel) { h.ch = ch; fmt.Println("connect done -> command handler open") }
func (h *CommandHandler) Send(text string) {
	fmt.Println("command: send", text)
	h.ch.messages = append(h.ch.messages, text)
}

type Acceptor struct {
	make     func() *StatusHandler
	handlers []*StatusHandler
}

var listeners = map[string]*Acceptor{} // stands in for the network

func Listen(address string, make func() *StatusHandler) *Acceptor {
	a := &Acceptor{make: make}
	listeners[address] = a
	fmt.Println("listen", address)
	return a
}

func (a *Acceptor) Accept(ch *Channel) {
	h := a.make()
	h.Open(ch)
	a.handlers = append(a.handlers, h)
}

func Connect(address string, make func() *CommandHandler) *CommandHandler {
	fmt.Println("connect", address)
	ch := &Channel{}
	listeners[address].Accept(ch)
	h := make() // complete: activate when the connection is up
	h.Open(ch)
	return h
}

func main() {
	acceptor := Listen("gateway:9000", func() *StatusHandler { return &StatusHandler{} })
	command := Connect("gateway:9000", func() *CommandHandler { return &CommandHandler{} })
	command.Send("reset")
	acceptor.handlers[0].Poll()
}
Output
listen gateway:9000
connect gateway:9000
accept -> status handler open
connect done -> command handler open
command: send reset
status: got reset
  • Verdict: idiom. A function value that returns a new handler is the factory.
RustGitHub
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::rc::Rc;

type Channel = Rc<RefCell<VecDeque<String>>>;

trait ServiceHandler {
    fn open(channel: Channel) -> Self;
}

struct StatusHandler { channel: Channel }
impl ServiceHandler for StatusHandler {
    fn open(channel: Channel) -> Self {
        println!("accept -> status handler open");
        StatusHandler { channel }
    }
}
impl StatusHandler {
    fn poll(&self) {
        let message = self.channel.borrow_mut().pop_front().unwrap();
        println!("status: got {}", message);
    }
}

struct CommandHandler { channel: Channel }
impl ServiceHandler for CommandHandler {
    fn open(channel: Channel) -> Self {
        println!("connect done -> command handler open");
        CommandHandler { channel }
    }
}
impl CommandHandler {
    fn send(&self, text: &str) {
        println!("command: send {}", text);
        self.channel.borrow_mut().push_back(text.to_string());
    }
}

struct Acceptor<H: ServiceHandler> { handlers: Vec<H> }
impl<H: ServiceHandler> Acceptor<H> {
    fn accept(&mut self, channel: Channel) {
        self.handlers.push(H::open(channel));
    }
}

fn connect<H: ServiceHandler>(address: &str, listeners: &mut HashMap<String, Acceptor<StatusHandler>>) -> H {
    println!("connect {}", address);
    let channel: Channel = Rc::new(RefCell::new(VecDeque::new()));
    listeners.get_mut(address).unwrap().accept(Rc::clone(&channel));
    H::open(channel) // complete: activate when the connection is up
}

fn main() {
    let mut listeners: HashMap<String, Acceptor<StatusHandler>> = HashMap::new();
    listeners.insert("gateway:9000".to_string(), Acceptor { handlers: Vec::new() });
    println!("listen gateway:9000");
    let command: CommandHandler = connect("gateway:9000", &mut listeners);
    command.send("reset");
    listeners["gateway:9000"].handlers[0].poll();
}
Output
listen gateway:9000
connect gateway:9000
accept -> status handler open
connect done -> command handler open
command: send reset
status: got reset
  • Verdict: idiom. The trait has a constructor-like open, so the generic acceptor and connector can create a handler of the type parameter. Rc<RefCell<...>> lets both handlers share the channel in one thread.

Consequences

Benefits:1

  • Reuse, portability and extension. The application-independent mechanisms in the Acceptor and Connector are reusable components that know how to establish connections and initialize the associated Service Handler.1
  • Local variation. By parameterizing the Acceptor and Connector with a Service Handler, the impact of this variation is localized to a small number of components in the software.1
  • Independent strategies. The initialization strategy and the service handling strategy are decoupled, so each strategy can evolve independently.1

Drawbacks:1

  • Additional indirection. The pattern can incur additional indirection compared with using the underlying network programming interfaces directly.1
  • Additional complexity. The pattern may add unnecessary complexity for simple client applications that connect with a single server and perform a single service.1

The connector must activate its handler only when the connection is complete. A common mistake is to start the service when the connect call starts. With an asynchronous connect, the first message then goes nowhere:

This code runs but gives a wrong answer on purpose.

class Connection:
    def __init__(self):
        self.established = False
        self.delivered = []

    def send(self, message):
        if self.established:
            self.delivered.append(message)
        # before the connection is up, the message is lost


def open_handler(connection):
    connection.send("hello")


connection = Connection()
open_handler(connection)  # activated when the connect starts
connection.established = True  # the asynchronous connect completes later
print("delivered:", connection.delivered)
Output
delivered: []

The fix is to call the hook method of the handler from the method that completes the connection.1

When not to use it

  • The program is a small client that connects to one server for one service.1
  • A framework already does the set-up, for example a web framework that calls a request handler. The program then writes only the service handler.
  • Template Method and Factory Method. The Acceptor's accept and the Connector's connect and complete functions are Template Methods.1 The Factory Method pattern is used to decouple the creation of a Service Handler from its subsequent use.1
  • Reactor and Proactor. They tell the acceptor and the connector when a connection is ready or done. POSA2 puts the four patterns in its event handling patterns.2
  • Server frameworks. In Python, socketserver asks for a request handler class with a handle() method, and a server class that is passed the server's address and the request handler class.3 The server is the acceptor and the handler class is the service handler. Here the client side is a plain connect:
import socket
import socketserver
import threading


class StatusHandler(socketserver.BaseRequestHandler):  # the service handler
    def handle(self):
        command = self.request.recv(100).decode()
        print("status: got", command)
        self.request.sendall(b"ok")


with socketserver.TCPServer(("127.0.0.1", 0), StatusHandler) as server:  # the acceptor
    worker = threading.Thread(target=server.handle_request)
    worker.start()
    with socket.create_connection(server.server_address) as client:  # the connector
        client.sendall(b"reset")
        print("command: reply", client.recv(100).decode())
    worker.join()
Output
status: got reset
command: reply ok

Known uses

  • UNIX superservers. inetd and similar daemons utilize a master Acceptor process that listens for connections on a set of communication ports.1 Each port is associated with a service such as ftp, telnet, daytime or echo.1
  • ACE. Implementations of the Service Handler, Connector, and Acceptor classes are provided as reusable components in the ACE object-oriented network programming framework.1
  • CORBA ORBs. The ORB Core layer in many implementations of CORBA uses the pattern to passively initialize server object implementations.1
  • Web browsers. Netscape and Internet Explorer use the asynchronous version of the connector component to establish connections with servers associated with images embedded in HTML pages.1
  • Python socketserver. The server class does the passive set-up, and the request handler class holds the service.3

References

  1. Douglas C. Schmidt, Acceptor-Connector, An Object Creational Pattern for Connecting and Initializing Communication Services, Intent; Structure; Known Uses; Consequences; See Also
  2. Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Table of Contents, 3 Event Handling Patterns
  3. socketserver, A framework for network servers, Python documentation, Server Creation Notes

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/42HRJH/text.yaml