Skip to content

NextSync .NET library

Julien Clauzel edited this page Nov 11, 2026 · 3 revisions

The NextSync .NET library — drive a Next from your own C# program

NextSyncListener is the PC half of the NextSync .sync5 -listen Remote Explorer protocol as a .NET class library: your program listens on TCP port 2048, a ZX Spectrum Next dials in (the .sync5 dot's -listen / -L, ZX Next Remote's Listener, QLNextRemote on a Sinclair QL), and from then on you drive the machine — list folders, get and put files, mkdir / rmdir / rm / rename, drives, free space, who is listening, CRC-32 computed on the Next, release, quit. It is a port of the listener worker inside ZX-Next-Unite — the one the app's Remote Explorer runs — so the wire is the app's wire: same framing, checksums, retries, silence and goodbye rules. It exists so a custom Remote Explorer can be written in .NET.

Targets net45 — any .NET Framework 4.5 – 4.8 application (WinForms, WPF, console) — and netstandard2.0 — .NET Core 2.0+, .NET 5 / 6 / 7 / 8+, Mono
Namespace NextSync.Listener
NuGet package / assembly NextSyncListener
Release asset NextSyncListener-<tag>.zip on every release, beside the app binaries
Source extra/NextSyncListener/ in the ZX-Next-Unite repository
Dependencies none — the base class library only
License MIT

⚠️ Verification status. The library is proven against an in-process fake Next that replays the dot's half of the protocol exactly as the mocks in the app's own test suite do (the executable spec the Python worker is held to): 27 tests, every op, a put through a forced retry and restart, OS protection, a Next that hangs up. On real hardware — a ZX Spectrum Next running .sync5 5.9.14, 2026-11-11 — the sample app's run was clean: the handshake, the version ident, drives, a 50-entry listing, free space and the quit. Put, get and CRC-32 have not been run against a real Next yet: their retry framing rests on the fake Next alone. The wire is byte-identical to the app's by construction; treat that run as yours to do.

Contents

Installation

From NuGet (once the package is published — see releases):

dotnet add package NextSyncListener

or in the project file:

<PackageReference Include="NextSyncListener" Version="9.7.*" />

NuGet picks the right build for your project by itself: a .NET Framework 4.5 – 4.8 project gets the net45 assembly, everything newer the netstandard2.0 one.

From the release zip. NextSyncListener-<tag>.zip holds two folders, net45/ and netstandard2.0/, each with NextSyncListener.dll, its XML documentation (IntelliSense) and symbols (.pdb), plus the README and the license. Add a reference to the dll from the folder matching your target (Visual Studio: References → Add Reference → Browse; SDK-style project: <Reference Include="NextSyncListener"><HintPath>...\net45\NextSyncListener.dll</HintPath></Reference>).

The Next side needs nothing new: any .sync5 dot with -listen (5.0+), ZX Next Remote's Listener, or a QLNextRemote job. Newer builds answer more ops — the API reference says which op needs which build; an older listener simply reports NotSupported for an op it does not know, and the session carries on.

Quick start — .NET 8

A console app (dotnet new console, add the package), the whole program:

using NextSync.Listener;

using var listener = new NextSyncListener();                 // every interface, port 2048
listener.Log += (s, e) => Console.WriteLine("[" + e.Level + "] " + e.Message);
listener.Connected += (s, e) => Console.WriteLine("A Next dialed in from " + e.RemoteEndPoint);
listener.Disconnected += (s, e) => Console.WriteLine("The Next left: " + e.Reason);
listener.Progress += (s, e) =>
{
    if (e.Kind == TransferKind.Put)
        Console.WriteLine("  " + e.RemotePath + ": " + e.BytesDone + " / " + e.BytesTotal);
};

listener.Start();
Console.WriteLine("Listening on port " + listener.LocalPort + " — on the Next run: .sync5 -listen");

// Commands queue until a Next is seated and polls; each Task completes when
// the Next has answered.
IdentResult who = await listener.QueryIdentAsync();
Console.WriteLine(who.Ok ? "Listener: " + who.Ident : "Listener predates the version query");

ListingResult listing = await listener.ListAsync("/games");
if (!listing.Ok)
{
    Console.WriteLine("ls failed: " + listing.Status + " — " + listing.Error);
}
else
{
    foreach (RemoteEntry entry in listing.Entries)
        Console.WriteLine(entry.IsDirectory ? "   <DIR>       " + entry.Name
                                            : "   " + entry.Size.ToString().PadLeft(9) + "  " + entry.Name);
}

PutResult put = await listener.PutAsync(@"C:\builds\game.nex", "/games/");  // trailing / = into that folder
Console.WriteLine(put.Ok ? "sent " + put.BytesSent + " bytes" : "put failed: " + put.Error);

// Verify it the way the app does: the Next computes the CRC-32 of its copy.
byte[] local = File.ReadAllBytes(@"C:\builds\game.nex");
CrcResult crc = await listener.GetCrc32Async("/games/game.nex");
if (crc.Ok)
    Console.WriteLine(crc.Crc32 == Crc32.Compute(local) ? "verified" : "MISMATCH: the copy on the card is corrupt");
else if (crc.Status == NextSyncStatus.NotSupported)
    Console.WriteLine("this listener cannot compute a CRC (dot < 5.9.2 / ZXNR < 1.0.8)");

GetResult back = await listener.GetAsync("/games/game.nex", @"C:\downloads");
Console.WriteLine(back.Ok ? "fetched to " + back.LastLocalPath : back.Error);

await listener.QuitAsync();   // the Next leaves listen mode (back to BASIC)
listener.Stop();

Run it, then on the Next type .sync5 -listen (the dot must already know this PC's address — the same .sync5 setup the app's NextSync tab walks through).

Quick start — .NET Framework 4.5

The library compiles for net45 and its API needs nothing newer than Task<T>: no await is required. .Result / .Wait() block only the calling thread — every completion runs on the thread pool, never on the listener's own thread — so this is safe:

using System;
using NextSync.Listener;

namespace NextDeploy
{
    class Program
    {
        static void Main()
        {
            using (var listener = new NextSyncListener())          // port 2048
            {
                listener.Log += (s, e) => Console.WriteLine(e.Message);
                listener.Connected += (s, e) => Console.WriteLine("Next at " + e.RemoteEndPoint);
                listener.Start();
                Console.WriteLine("On the Next: .sync5 -listen");

                var listing = listener.ListAsync("/").Result;   // waits for a Next if none is seated
                if (listing.Ok)
                {
                    foreach (var entry in listing.Entries)
                        Console.WriteLine(entry);               // "<DIR> GAMES", "1234 boot.bas"
                }
                else
                {
                    Console.WriteLine(listing.Status + ": " + listing.Error);
                }

                var put = listener.PutAsync(@"C:\builds\game.nex", "/games/").Result;
                Console.WriteLine(put.Ok ? "sent " + put.BytesSent + " bytes" : put.Error);

                var drives = listener.GetDrivesAsync().Result;
                if (drives.Ok)
                    Console.WriteLine("Current drive " + drives.Current + ", mounted: " + string.Join(" ", drives.Mounted));

                listener.QuitAsync().Wait();
                listener.Stop();
            }
        }
    }
}

In a WinForms or WPF application two rules keep the window alive:

  • the events (Connected, Disconnected, Log, Progress) arrive on the listener's own threads — marshal before touching a control:

    listener.Log += (s, e) => BeginInvoke((Action)(() => logBox.AppendText(e.Message + "\r\n")));
  • never .Result on the UI thread (the window would freeze until the Next answers). Continue on the thread pool instead and marshal the result:

    listener.ListAsync("/games").ContinueWith(t =>
        BeginInvoke((Action)(() => ShowListing(t.Result))));

    (.NET 4.5's C# 5 compiler also supports async / await in an event handler — private async void refresh_Click(...) { var r = await listener.ListAsync("/"); ... } — which does the same marshalling for you.)

How it behaves

The Next drives. It polls the server every second or two; every poll is answered with exactly one command (or the idle I), and the Next pushes the reply back as framed blocks the server acks one by one. Your program sees a queue: each *Async call puts a command on it and returns a Task that completes when the Next has answered. Nothing is sent until the Next polls, so a command queued before any Next has dialed in simply waits.

One seat. The first Next to send the Listen handshake is seated; a second one dialing in meanwhile is told Busy (the dot prints Server busy) and closed. When the seated Next leaves — a quit, a hang-up, silence — the listener goes on accepting, and Disconnected says why it ended.

The queue rule. A command queued while no Next was connected waits for the next one to dial in. A command queued while a Next was connected fails with Cancelled if that Next leaves before it ran: it is never run on a different machine (its card is not the one you meant). A command already in flight cannot be cancelled — a half-written file on the card is worse than a slow cancel — but a queued one can, through a CancellationToken.

Statuses, not exceptions. A result's Status says how it went; the *Async methods throw only for bad arguments. In particular the Next's two refusals are told apart: a plain F (Failed: the file did not open, the folder is not empty...) and ZX Next Remote's OS protection refusal (OsProtected), which is a setting on the Next — it guards /nextzxos, /sys, /dot and friends — not a network problem.

Puts are served in MaxPayload-byte frames (512 by default: Next clones corrupt longer UART bursts) at the pace the Next pulls them. A Retry from the Next resends the same frame, a Restart serves the file from the top; PutResult counts both. The Task completes when the last data frame has been served; the Next then pulls one empty frame as its end of file. With VerifyPuts on, every put is followed by the Next's own CRC-32 against the bytes sent, on listeners known to answer it: a different digest deletes the corrupted copy and fails the put (CrcMismatch); silence, an F or a malformed digest keep the file and report the put done but Verified = false.

Gets of a folder stream every file with its full Next path. They are written under the fetched folder's own name (/games/lev lands as <dest>/lev/..., sub-folders kept), never under a copy of the whole Next path, and never outside the destination folder whatever a name says.

Timeouts. ReplyTimeout (60 s) bounds the silence between two blocks of one reply — the Next can legitimately pause for seconds. CrcTimeout (1 hour) bounds a K: the Next reads the whole file before it answers (~30 s per MB on the dot). PeerSilenceLimit (620 s, the app's value, paired with ZX Next Remote's own dead-link guard) is silence between commands: the Next drives, so a seat that stops polling is gone. Stop() sends the seated Next a Q at its next poll (it returns to BASIC), waits up to the grace period, then closes.

Late polls. A Next that re-polls while the reply to a mkdir, rmdir or rm is owed is late, not gone (it missed the command inside its own window): the poll is swallowed once and the reply awaited. For every other op the raw poll keeps its old reading — "I do not know that opcode", which is how an older dot answers Y, K, U, W or Z — and the result is NotSupported.

API reference

Everything lives in the namespace NextSync.Listener.

NextSyncListener

public sealed class NextSyncListener : IDisposable

Constructors

NextSyncListener() every IPv4 interface, port 2048
NextSyncListener(int port) every IPv4 interface; port 0 lets the OS pick (see LocalPort)
NextSyncListener(IPAddress bindAddress, int port) one address

Properties

Property Default Meaning
BindAddress IPAddress.Any the address the socket binds to
Port 2048 the port asked for (DefaultPort)
LocalPort — the port actually bound once started
MaxPayload 512 (DefaultMaxPayload) bytes per served put frame, 1–1024; 512 because Next clones (N-Go) corrupt longer UART bursts
ReplyTimeout 60 s the quiet allowed between two blocks of one reply before the command is reported dropped
CrcTimeout 1 h the wait for a K answer
PeerSilenceLimit 620 s silence between commands after which the seated Next is assumed gone
HandshakeTimeout 10 s how long a new connection may take to send its 6-byte Listen
GoodbyeLinger 2 s how long a sent Q is given to be read before the socket closes (a Bye meanwhile is answered Later)
VerifyPuts false follow every put with the Next's CRC-32 (the app's Verify CRC setting; off here because the check costs the Next a full read of the file)
IsListening true between Start() and Stop()
IsConnected true while a Next is seated
RemoteEndPoint the seated Next's address, or null
Ident the seated Next's NextIdent once queried (by QueryIdentAsync or a put verification), else null

Lifecycle

Method Does
void Start() binds and starts the accept thread. On Windows the port is bound exclusively (a second instance fails cleanly instead of silently stealing it); on POSIX with SO_REUSEADDR. Throws SocketException when the port is taken.
void Stop() Stop(TimeSpan.FromSeconds(5))
void Stop(TimeSpan gracePeriod) stops accepting; if a Next is seated sends it a Q at its next poll and waits up to the grace period; then closes everything. Queued commands fail with Cancelled. The listener can be started again.
void Dispose() Stop(2 s), then the instance is done

Commands — every one takes an optional trailing CancellationToken and returns a Task<…Result>; "needs" names the oldest listener build that answers the op (older ones report NotSupported).

Method Wire Result Needs
ListAsync(string path) L ListingResult — empty path = the dot's current folder any
GetAsync(string remotePath, string localDirectory) G GetResult — a file, or a whole folder recreated under its own name any
GetBytesAsync(string remotePath) G GetResult with the bytes in Data any
PutAsync(string localFile, string remotePath) P PutResult — a remotePath ending in / means "into that folder" (the local file name is appended); the file is read when the command is served, so a missing file is a LocalError result, not an exception any
PutAsync(byte[] data, string remotePath) P PutResult — the remote path must name the file (a trailing / throws) any
MakeDirectoryAsync(string path) M StatusResult — note esxDOS answers F for "exists" too any
RemoveDirectoryAsync(string path) R StatusResult — an EMPTY folder only any
DeleteFileAsync(string path) X StatusResult any
RenameAsync(string oldPath, string newPath) V StatusResult — a rename onto an existing name is refused by NextZXOS any
ReleaseAsync() U StatusResult — the far side closes its own file handle so its running file can be swapped; send only path-based ops afterwards (rename, delete, quit) dot 5.9 / ZXNR 1.0.3
GetDrivesAsync() W DrivesResult dot 5.1
GetFreeSpaceAsync(string drive = "") Z FreeSpaceResult — "M", "m:", or empty for the current drive dot 5.2
QueryIdentAsync() Y IdentResult — cached on Ident dot 5.8 / ZXNR 1.0.2
GetCrc32Async(string path) K CrcResult dot 5.9.2 / ZXNR 1.0.8 / QLNR 0.1.0
CopyOnNextAsync(string source, string destination) C CopyResult — the copy runs ON the Next, across partitions too; already-copied files stay on a failure dot 5.2
GetSizeAsync(string path) S SizeResult — a file or a whole tree dot 5.2
DeleteTreeAsync(string path) L / X / R DeleteTreeResult — esxDOS removes empty folders only, so the tree is walked bottom-up, one step per poll, ahead of anything else queued; a plain refusal is counted and the walk carries on, an OS-protection refusal ends it any
QuitAsync(bool exitApplication = false) Q / Q+X QuitResult — the Next leaves listen mode; with exitApplication it also ends its application (ZX Next Remote 0.9.47+; a dot exits to BASIC either way). The session ends; the listener keeps accepting any

Events — all raised on the listener's accept or session thread; an exception thrown by a handler is swallowed so it cannot end the session.

Event Args When
Connected NextConnectedEventArgs a Next was seated
Disconnected NextDisconnectedEventArgs the session ended — Reason says how
Log ListenerLogEventArgs a console-style line (what the app prints on its NextSync console)
Progress TransferProgressEventArgs a put frame served, a get block received, a copy or size walk item named

Results

public class NextSyncResult — the base of every result:

Member Meaning
NextSyncStatus Status how the command ended (below)
string Error a human-readable reason when not Ok (English, the worker's wording)
bool Ok Status == Ok
bool IsOsProtected Status == OsProtected

public enum NextSyncStatus:

Value Meaning
Ok the Next did what was asked
Failed the Next answered a plain F: the file did not open, the folder is not empty, the rename was refused...
OsProtected the marked F+OSP refusal: ZX Next Remote's OS protection — check that setting on the Next
NotSupported the listener predates this opcode (it answered with silence and polled on)
ConnectionDropped the reply never completed: the link dropped, the reply timed out, or a frame was malformed
Cancelled taken off the queue before it ran: a cancellation token, Stop(), or the Next it was queued for left
LocalError a local problem before a byte moved (a file that could not be read, a folder that could not be created)

The typed results, all sealed and derived from NextSyncResult:

Type Members
ListingResult string Path; IList<RemoteEntry> Entries — directories first, then by name, case-insensitively (the Remote Explorer's order)
RemoteEntry string Name; bool IsDirectory; long Size
GetResult string RemotePath; IList<ReceivedFile> Files (arrival order); long BytesReceived; byte[] Data (the first file's bytes, in-memory gets); string LastLocalPath (gets to a folder)
ReceivedFile string RemoteName (as the Next sent it — a full Next path for a folder get); string LocalPath (null for in-memory); byte[] Data (null when written to disk); long Length
PutResult string RemotePath; long BytesSent; long BytesTotal; int Retries; int Restarts; bool Verified; string VerificationNote; bool CrcMismatch
StatusResult string Operation (mkdir / rmdir / rm / rename / release); string Path
DrivesResult string Current (e.g. "C"); IList<string> Mounted (e.g. C, M)
FreeSpaceResult string Drive (normalised: m: → M; empty = current); long FreeBytes (free 512-byte blocks × 512 — the only storage metric a dot can obtain safely)
IdentResult NextIdent Ident (null when the listener predates Y)
CrcResult string Path; string Crc32Hex (8 upper-case hex digits, as answered); uint Crc32
CopyResult string Source; string Destination; int FilesCopied
SizeResult string Path; long Files; long Directories; long Bytes (48 bits on the wire)
DeleteTreeResult string Root; int FilesDeleted; int FoldersDeleted; int Failures
QuitResult bool ExitApplication

public sealed class NextIdent — string Type (sync for the dot, httpbridge / n2n / zxnt for ZX Next Remote, qlnextremote / qlnt for a QL job), string Version (e.g. 5.9.14), bool AnswersCrc (whether this build is known to answer K, per CrcFloors).

Events

Type Members
NextConnectedEventArgs IPEndPoint RemoteEndPoint
NextDisconnectedEventArgs IPEndPoint RemoteEndPoint; string Reason — "quit sent", "the Next closed the connection", "no word from the Next for 620s - assuming it is gone...", "connection error from the Next (...)", "the listener was stopped"
ListenerLogEventArgs ListenerLogLevel Level (Info / Warning / Error); string Message
TransferProgressEventArgs TransferKind Kind (Put / Get / Copy / Size); string RemotePath; long BytesDone; long BytesTotal (the file size for a put, −1 for a get: the wire never says); int Files; string Item (the file being received / copied, the directory being scanned; empty for a keepalive)

Helpers

Type Members
static class NextSyncFraming the block framing [2 B big-endian total][payload][checksum0][checksum1][packetno]: Checksums(byte[] data, int offset, int count, out byte c0, out byte c1); byte[] Build(byte[] payload, byte packetNo) (+ range and string overloads); bool TryParse(byte[] data, int offset, int available, out byte[] payload, out byte packetNo, out bool checksumOk, out int total); constants HeaderSize 2, TrailerSize 3, MinTotal 5, MaxTotal 4096, MaxPayloadCap 1024
static class Crc32 uint Compute(byte[] data) / Compute(byte[] data, int offset, int count) — the IEEE CRC-32 the Next's K computes (zlib.crc32's value); string ToHex(uint crc) — the 8 upper-case digits
static class CrcFloors bool PeerAnswersCrc(string type, string version) — the builds that answer K (the app's RE_CRC_FLOORS: sync 5.9.2, httpbridge / n2n 1.0.8, zxnt 1.6.0, qlnextremote / qlnt 0.1.0); int[] ParseVersion(string); int Compare(int[] a, int[] b)
static class OsProtection byte[] Marker (OSP); string ErrorText (the app's explanation); bool IsRefusal(byte[] payload)
static class RemotePaths string SanitizeIncomingPath(string root, string name) — a received name mapped to a safe path under root (drive letters and .. stripped, never outside the root); string RelativeNameUnder(string remote, string name) — a folder get's full Next path reduced to its path under the fetched folder; string BaseName(string remotePath)

What is not in the library

On purpose, because the library is the listener and nothing else: the classic Sync3/Sync4 sync server (the .sync5 folder sync), the HTTP bridge, the app's multi-seat roster and baton, the "Sessions Off" eviction and link-loss retries, the remote self-update macro (.sync5 / ZX Next Remote over the wire) and the QL / Next stale-seat rules. Three small, documented differences from the app's worker: a link that dies under an optional op's reply reports ConnectionDropped, never "not supported"; a put whose local file cannot be read answers that poll with an idle (the worker leaves it unanswered); Stop() sends a Q before closing.

Building from source, tests, releases

git clone https://github.com/jclauzel/ZX-Next-Unite.git
cd ZX-Next-Unite/extra/NextSyncListener
dotnet build NextSyncListener.sln          # the library (both targets), the sample, the tests
dotnet test Tests/Tests.csproj             # 27 tests against the fake Next
dotnet run --project Sample -- 2048 /      # start, wait for a Next, list its root

The .NET SDK 8 or newer is all it needs; the net45 target builds without a .NET Framework targeting pack (the Microsoft.NETFramework.ReferenceAssemblies package provides it), on Linux and macOS too. The source stays inside what both targets can consume — C# 7.3, no Span, no ValueTuple, no init-only setters, no default interface members.

Releases. The dotnet-nextsync workflow builds and tests the library on every change under extra/NextSyncListener/. On a v* tag it packs the library with the tag as its version and attaches NextSyncListener-<tag>.zip and the .nupkg to the draft GitHub release the app's release workflow creates. The package is pushed to NuGet only when that release is published — so the NuGet version always equals an app release's tag.

Publishing to NuGet uses nuget.org's Trusted Publishing (OIDC), the same mechanism the app's PyPI publish uses: no API key is stored anywhere (nuget.org now marks stored keys "not recommended"). The workflow's NuGet/login step exchanges the job's short-lived GitHub token for a one-hour NuGet key against a trust policy on nuget.org, which is the one-time setup: sign in, open the account menu → Trusted Publishing → add a policy with Repository Owner jclauzel, Repository ZX-Next-Unite, Workflow File dotnet-nextsync.yml (the file name only, no path) and Environment left empty. A new policy is temporarily active for 7 days; the first successful login binds it to the repository and makes it permanent, and the window can be restarted from the same page if it lapses. The package id NextSyncListener is claimed by the first push.

Troubleshooting

Symptom Cause / fix
Start() throws SocketException (address in use) something already listens on 2048 — ZX-Next-Unite's own Remote Explorer or classic sync server, nextsync5.py, or another instance of your program. Stop it, or pick another port (the Next must then be told it: .sync5 takes the port with the server address).
The Next says Server busy a Next is already seated (one seat). Quit that one first (QuitAsync) or wait for Disconnected.
The Next says Server too old (-listen) your program answered its Listen with something other than the framed Listening. Nothing to fix in the library — check nothing else sits on the port.
A command's Task never completes no Next is seated yet (commands wait for the next one to dial in — pass a CancellationToken to bound the wait), or the Next is busy with a long op (a K on a big file, a multi-megabyte put).
ConnectionDropped on every command, then Disconnected the link really died (Wi-Fi, power), or the Next was reset under a live ESP link: it is reaped at PeerSilenceLimit.
NotSupported the listener on the Next predates that op; the table above says which build it needs. Update the .sync5 dot (the app's Remote Explorer can push it over the wire) or ZX Next Remote.
OsProtected ZX Next Remote's OS protection refused a write (or a read, with Read+write) under a guarded folder. Change the setting on the Next, or the folder.
A put is slow normal: the Next pulls 512-byte frames over a UART; .sync5 -f / ZX Next Remote's Fast rate help. MaxPayload = 1024 is faster on real Nexts and the dot, but corrupts on clones.
Events arrive on strange threads by design — marshal to your UI thread (see the .NET Framework quick start).

Clone this wiki locally