Skip to content

CefServer

Header: cef_server.h
Interfaces: CefServer, CefServerHandler
Category: System Utilities

Overview

Tasks, threads, parsers, streams, cookies, URL requests, scheme registration, and constant tables.

CefServer

Source File: include/cef_server.h

Process / Thread Context: Browser Process. Methods are safe to call from any thread in the browser process unless otherwise indicated. Several methods explicitly require the dedicated server thread (IsRunning, HasConnection, IsValidConnection).

Purpose: Class representing a server that supports HTTP and WebSocket requests. Capacity is limited and intended to handle only a small number of simultaneous connections (e.g. for communicating between applications on localhost). Each CreateServer call spins up a dedicated server thread.

Methods

static void CreateServer(const CefString& address, uint16_t port, int backlog, CefRefPtr<CefServerHandler> handler)

Parameters:

  • address: Valid IPv4 or IPv6 address (e.g. "127.0.0.1" or "::1").
  • port: Port number outside the reserved range (typically 1025–65535).
  • backlog: Maximum number of pending connections.
  • handler: A CefServerHandler implementation. A new dedicated server thread is created per CreateServer call; it is recommended to use a different handler instance per call to avoid thread-safety issues.

Return Value: Returns void. Asynchronously, CefServerHandler::OnServerCreated is called on the dedicated server thread to report success or failure.

Usage Instruction: Call from the browser process to start a server. The handler owns the lifespan — see CefServerHandler::OnServerCreated documentation.

Threading Constraint: May be called from any thread in the browser process.

virtual CefRefPtr<CefTaskRunner> GetTaskRunner()

Parameters:

  • None.

Return Value: Returns the task runner for the dedicated server thread.

Usage Instruction: Use to post tasks to the server thread, e.g. to drive connection handling from another thread.

Threading Constraint: Not specified.

virtual void Shutdown()

Parameters:

  • None.

Return Value: Returns void. Stops the server and shuts down the dedicated server thread.

Usage Instruction: Call to cleanly stop the server. OnServerDestroyed will be invoked on the server thread after shutdown completes.

Threading Constraint: Safe to call from any thread in the browser process (per the class-level comment).

virtual bool IsRunning()

Parameters:

  • None.

Return Value: Returns true if the server is currently running and accepting incoming connections.

Usage Instruction: Use to check server status before issuing per-connection methods.

Threading Constraint: Must be called on the dedicated server thread.

virtual CefString GetAddress()

Parameters:

  • None.

Return Value: Returns the server address including the port number.

Usage Instruction: Use to log or share the bound address/port with clients.

Threading Constraint: Not specified (safe from any thread per class comment).

virtual bool HasConnection()

Parameters:

  • None.

Return Value: Returns true if the server currently has at least one connection.

Usage Instruction: Use for idle detection or for graceful shutdown logic.

Threading Constraint: Must be called on the dedicated server thread.

virtual bool IsValidConnection(int connection_id)

Parameters:

  • connection_id: A connection ID previously delivered to the handler via OnClientConnected (or any of the request callbacks).

Return Value: Returns true if connection_id represents a valid (currently open) connection.

Usage Instruction: Use to check whether a stored connection ID is still usable before issuing a send.

Threading Constraint: Must be called on the dedicated server thread.

virtual void SendHttp200Response(int connection_id, const CefString& content_type, const void* data, size_t data_size)

Parameters:

  • connection_id: Connection ID to respond to.
  • content_type: Response content type (e.g. "text/html").
  • data: Response content buffer.
  • data_size: Size of data in bytes; data will be copied internally.

Return Value: Returns void. The connection is closed automatically after the response is sent.

Usage Instruction: Use for the simplest "OK + body" HTTP responses.

Threading Constraint: Not specified (typically the server thread).

virtual void SendHttp404Response(int connection_id)

Parameters:

  • connection_id: Connection ID to respond to.

Return Value: Returns void. Connection closed automatically after the response is sent.

Usage Instruction: Use for a minimal 404 response.

Threading Constraint: Not specified.

virtual void SendHttp500Response(int connection_id, const CefString& error_message)

Parameters:

  • connection_id: Connection ID to respond to.
  • error_message: Associated error message body.

Return Value: Returns void. Connection closed automatically after the response is sent.

Usage Instruction: Use to report server-side errors with a custom message.

Threading Constraint: Not specified.

virtual void SendHttpResponse(int connection_id, int response_code, const CefString& content_type, int64_t content_length, const HeaderMap& extra_headers)

Parameters:

  • connection_id: Connection ID to respond to.
  • response_code: HTTP response code (e.g. 200, 404, 500).
  • content_type: Value for the "Content-Type" header.
  • content_length: Expected content length. If >= 0 the "Content-Length" header is sent. If 0 no content is expected and the connection closes after the response. If < 0 no "Content-Length" header is sent and the client reads until connection close.
  • extra_headers: Map of extra response headers. May be empty.

Return Value: Returns void. After this call, use SendRawData to deliver content and CloseConnection to terminate the response.

Usage Instruction: Use for arbitrary HTTP responses (custom status, headers, streamed body). Pair with SendRawData + CloseConnection.

Threading Constraint: Not specified.

virtual void SendRawData(int connection_id, const void* data, size_t data_size)

Parameters:

  • connection_id: Connection ID to send data to.
  • data: Raw data buffer; contents will be copied.
  • data_size: Size of data in bytes.

Return Value: Returns void. No internal validation of data is performed — the caller must send the amount indicated by the "Content-Length" header if one was set.

Usage Instruction: Call after SendHttpResponse to stream the body. Call multiple times for chunked output. Finish with CloseConnection.

Threading Constraint: Not specified.

virtual void CloseConnection(int connection_id)

Parameters:

  • connection_id: Connection ID to close.

Return Value: Returns void.

Usage Instruction: Call after the last SendRawData to terminate the response. Subsequent OnClientDisconnected will be delivered to the handler.

Threading Constraint: Not specified.

virtual void SendWebSocketMessage(int connection_id, const void* data, size_t data_size)

Parameters:

  • connection_id: Connection ID (must be one that has been accepted as a WebSocket via the OnWebSocketRequest callback).
  • data: Response content; copied internally.
  • data_size: Size of data in bytes.

Return Value: Returns void. Sends a WebSocket message frame to the client.

Usage Instruction: Call only after OnWebSocketConnected has fired for that connection_id. Do not retain the data pointer past the call.

Threading Constraint: Not specified.

Usage Example

cpp
// === Boot a localhost HTTP server that echoes requests as JSON ===

class EchoHandler : public CefServerHandler {
 public:
  void OnServerCreated(CefRefPtr<CefServer> srv) override {
    server_ = srv;
    LOG(INFO) << "listening on " << srv->GetAddress().ToString();
  }
  void OnServerDestroyed(CefRefPtr<CefServer>) override { server_ = nullptr; }
  void OnClientConnected(CefRefPtr<CefServer>, int) override {}
  void OnClientDisconnected(CefRefPtr<CefServer>, int) override {}

  void OnHttpRequest(CefRefPtr<CefServer> srv, int conn,
                     const CefString& addr,
                     CefRefPtr<CefRequest> req) override {
    std::string body = "{\"url\":\"" + req->GetURL().ToString() + "\"}";
    srv->SendHttp200Response(conn, "application/json",
                             body.data(), body.size());
  }

  void OnWebSocketRequest(CefRefPtr<CefServer> srv, int conn,
                          const CefString&, CefRefPtr<CefRequest>,
                          CefRefPtr<CefCallback> cb) override {
    cb->Continue();  // Accept the WebSocket upgrade.
  }
  void OnWebSocketConnected(CefRefPtr<CefServer>, int) override {}
  void OnWebSocketMessage(CefRefPtr<CefServer> srv, int conn,
                          const void* data, size_t n) override {
    srv->SendWebSocketMessage(conn, data, n);  // Echo.
  }

  CefRefPtr<CefServer> server_;
  IMPLEMENT_REFCOUNTING(EchoHandler);
};

void StartEchoServer() {
  CefServer::CreateServer("127.0.0.1", 8080,
                          /*backlog=*/10, new EchoHandler());
}

CefServerHandler

Source File: include/cef_server.h

Process / Thread Context: Browser Process / Dedicated Server Thread — a new thread is created per CefServer::CreateServer call and all handler methods are invoked on that thread. The header recommends using a different handler instance per server to avoid thread-safety issues.

Purpose: Implement this interface to handle HTTP server requests, WebSocket requests, connection lifecycle events, and server lifecycle events.

Methods

void OnServerCreated(CefRefPtr<CefServer> server)

Parameters:

  • server: The newly created server. If startup failed, OnServerDestroyed will be called immediately after this method returns.

Return Value: Returns void.

Usage Instruction: Cache the server pointer here if needed; check server->IsRunning() to determine success. The server will run until CefServer::Shutdown is called, after which OnServerDestroyed is invoked.

Threading Constraint: Dedicated server thread.

void OnServerDestroyed(CefRefPtr<CefServer> server)

Parameters:

  • server: The server being destroyed. The server thread will be stopped after this method returns.

Return Value: Returns void.

Usage Instruction: Release any references to server here. Subsequent calls to server methods are invalid.

Threading Constraint: Dedicated server thread.

void OnClientConnected(CefRefPtr<CefServer> server, int connection_id)

Parameters:

  • server: The originating server.
  • connection_id: A connection ID that uniquely identifies this connection. Each call has a matching OnClientDisconnected later.

Return Value: Returns void.

Usage Instruction: Use to track live connections, allocate per-connection state, or log connect events.

Threading Constraint: Dedicated server thread.

void OnClientDisconnected(CefRefPtr<CefServer> server, int connection_id)

Parameters:

  • server: The originating server.
  • connection_id: The disconnecting connection ID. The client should release any data associated with connection_id here; the ID must no longer be passed to CefServer methods.

Return Value: Returns void.

Usage Instruction: Disconnects can originate from either the client or the server (e.g. after SendHttpXXXResponse the server automatically disconnects). Use this to clean up per-connection state.

Threading Constraint: Dedicated server thread.

void OnHttpRequest(CefRefPtr<CefServer> server, int connection_id, const CefString& client_address, CefRefPtr<CefRequest> request)

Parameters:

  • server: The originating server.
  • connection_id: Connection ID.
  • client_address: IPv4 or IPv6 client address including the port number.
  • request: The request contents — URL, method, headers, optional POST data.

Return Value: Returns void.

Usage Instruction: Call CefServer methods synchronously or asynchronously (e.g. via GetTaskRunner()->PostTask) to send a response. The connection is not closed until a send/close method is invoked.

Threading Constraint: Dedicated server thread.

void OnWebSocketRequest(CefRefPtr<CefServer> server, int connection_id, const CefString& client_address, CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback)

Parameters:

  • server: The originating server.
  • connection_id: Connection ID for this WebSocket upgrade attempt.
  • client_address: IPv4 or IPv6 client address including port.
  • request: The request contents (URL, method, headers, optional POST data).
  • callback: Execute synchronously or asynchronously to accept or decline the WebSocket connection. callback->Continue() accepts; callback->Cancel() declines.

Return Value: Returns void.

Usage Instruction: If accepted, OnWebSocketConnected is called after the WebSocket has connected and incoming messages are delivered to OnWebSocketMessage. If declined the client is disconnected and OnClientDisconnected is called. Call CefServer::SendWebSocketMessage after OnWebSocketConnected to respond.

Threading Constraint: Dedicated server thread.

void OnWebSocketConnected(CefRefPtr<CefServer> server, int connection_id)

Parameters:

  • server: The originating server.
  • connection_id: Connection ID of the now-connected WebSocket.

Return Value: Returns void.

Usage Instruction: Use as the signal that you may now safely call CefServer::SendWebSocketMessage for this connection_id.

Threading Constraint: Dedicated server thread.

void OnWebSocketMessage(CefRefPtr<CefServer> server, int connection_id, const void* data, size_t data_size)

Parameters:

  • server: The originating server.
  • connection_id: Connection ID.
  • data: Message content buffer. Do not keep a reference to data outside this method.
  • data_size: Size of data in bytes.

Return Value: Returns void.

Usage Instruction: Process the inbound WebSocket frame. Copy data if you need it after the method returns. Call CefServer::SendWebSocketMessage to respond.

Threading Constraint: Dedicated server thread.

Derived from the CEF C++ headers — © Marshall A. Greenblatt, Google Inc. & contributors (BSD-style license). Not an official CEF project.