Hosting Remote Sessions
Repl can host multiple concurrent sessions over any transport that delivers a stream pair — a reader and a writer. Each session gets its own scope, history, and context; shared state is opt-in via DI singletons.
The built-in packages cover the most common cases:
Repl.WebSocket— raw WebSocket sessions, served from ASP.NET Core. Good for browser clients, reverse-proxy friendly.Repl.Telnet— the Telnet session protocol (framing, NAWS window size, terminal type) over a WebSocket, aStreamor anIDuplexPipe. For terminal emulators and Telnet clients.
Any other transport — SSH, TCP sockets, gRPC streams — works by instantiating StreamedReplHost with a TextWriter, pushing received text via EnqueueInput, and calling RunSessionAsync. For an operator console on the same machine, use Remote Administration, which ships a named-pipe endpoint.
WebSocket transport (Repl.WebSocket)
Section titled “WebSocket transport (Repl.WebSocket)”Add Repl.WebSocket, accept the socket in an ASP.NET Core endpoint, and hand it to ReplWebSocketSession. RunWithServicesAsync runs the session against the request’s services, so handlers resolve what the host registered:
using Repl;using Repl.WebSocket;
var builder = WebApplication.CreateBuilder(args);
// shared services — must be thread-safe (see caution below)builder.Services.AddSingleton<IContactStore, ContactStore>();
// define the command graph once, for every sessionbuilder.Services.AddRepl((_, repl) =>{ repl.UseEmbeddedConsoleProfile(); repl.Context("client", client => { client.Map("list", (IContactStore store) => store.All()); // ... });});
var app = builder.Build();app.UseWebSockets();
app.Map("/ws/repl", async (HttpContext context, ReplApp repl, IHostApplicationLifetime lifetime) =>{ if (!context.WebSockets.IsWebSocketRequest) { context.Response.StatusCode = StatusCodes.Status400BadRequest; return; }
using var socket = await context.WebSockets.AcceptWebSocketAsync(); using var session = CancellationTokenSource.CreateLinkedTokenSource( context.RequestAborted, lifetime.ApplicationStopping); try { await ReplWebSocketSession.RunWithServicesAsync(repl, socket, context.RequestServices, new ReplRunOptions { SessionScope = SessionScopeBehavior.CallerOwned }, cancellationToken: session.Token); } catch (OperationCanceledException) when (session.IsCancellationRequested) { // the client went away, or the host is stopping }});
app.Run();SessionScopeBehavior.CallerOwned makes the request scope the session scope: a service registered with AddScoped in the host resolves once per WebSocket connection. Linking ApplicationStopping ends open sessions when the host stops; otherwise a long-lived WebSocket request may only be aborted when the server’s shutdown timeout runs out.
ReplWebSocketSession.RunAsync(repl, socket, ct) also exists, but it runs on the Repl application’s own container, which does not see the host’s registrations.
Telnet session protocol (Repl.Telnet)
Section titled “Telnet session protocol (Repl.Telnet)”Repl.Telnet adds Telnet framing and terminal negotiation on top of a transport. To serve it over WebSocket, map a second endpoint like the one above and call ReplTelnetSession instead:
using Repl.Telnet;
await ReplTelnetSession.RunAsync(repl, socket, new ReplRunOptions(), session.Token);Other overloads accept a Stream or an IDuplexPipe, plus callbacks for window-size and terminal-type changes. Terminal size and type are negotiated automatically via NAWS (RFC 1073) and TERMINAL-TYPE (RFC 1091). Connect with a Telnet-to-WebSocket bridge, or with wscat pointed at that endpoint.
Terminal metadata
Section titled “Terminal metadata”Each session carries terminal metadata — capabilities and window size, injectable via ITerminalInfo (namespace Repl.Interaction):
using Repl.Interaction;
app.Map("info", (ITerminalInfo terminal) => new{ terminal.IsAnsiSupported, terminal.CanReadKeys, terminal.WindowSize,});Handlers can adapt output to the terminal width. IsAnsiSupported says whether the handler may drive the terminal; test Palette is not null to decide on color (see Adapting output to terminal capabilities).
Shared vs. per-session state
Section titled “Shared vs. per-session state”| Registration | Scope |
|---|---|
AddSingleton<T> | Shared across all sessions |
AddScoped<T> | One instance per session (per WebSocket connection with CallerOwned) |
AddTransient<T> | New instance per resolution |
Use AddScoped<T> for per-user state (shopping cart, selection, cursor position).
How a session ends
Section titled “How a session ends”- The client leaves. A peer that closes the connection ends the session normally. Telnet ends as soon as the peer closes its input, then sends the remaining output.
- Ctrl+C interrupts only the current command; the session stays open.
- The session’s token is cancelled, as when the sample above links host shutdown and the request abort. The running command and any waiting prompt are cancelled, and the session throws
OperationCanceledExceptionunlessExitCodes.Cancelledor a resolver maps it to a code. Catch it in the endpoint, as above. - A message is too large. Incoming WebSocket messages are limited to 64 KiB across all fragments; a larger one closes the session with
MessageTooBig(1009).
A WebSocket session closes the socket with a normal close handshake, waiting up to a second for the peer. When building on the Telnet blocks directly, dispose TelnetFraming before completing its pipe.
Further reading
Section titled “Further reading”- Dependency Injection — service lifetimes and how
AddScopedmaps to per-session state in hosted sessions. - Terminal Integration — terminal capability detection, ANSI support, and window-size negotiation.
- Pipelining & Lifecycle — hosted service integration and
ReplRunOptions. - Remote Administration — attach an operator console to the running process over a named pipe.