Windows-only asynchronous TCP connection. windows/TcpConnection starts Winsock overlapped connect, receive, and send operations and reports completion through windows/dispatcher; it is distinct from the fiber-based sync/TcpConnection.
Known issue: setConnection calls the unavailable copy helper, so accepting a connection through windows/TcpAcceptor or calling setConnection directly fails with Name was not found; construction and the other methods compile.
Object and construction
TcpConnectionis one object with an atomicNat32state word, one socket handle, one readdispatcher.Context, one writedispatcher.Context, and callback storage.INITsets the state word to0n32. Default construction therefore creates an unconnected object; this module has nomakeTcpConnectionhelper.- The state bits are
IN_DIE=0x00000001n32,IN_IS_CONNECTED=0x00000002n32,IN_SET=0x00000004n32,IN_CONNECT=0x00000008n32,IN_CANCEL_CONNECT=0x00000010n32,IN_DISCONNECT=0x00000020n32,IN_READ=0x00000040n32,IN_CANCEL_READ=0x00000080n32,IN_WRITE=0x00000100n32,IN_CANCEL_WRITE=0x00000200n32,IN_ON_CONNECT_EVENT=0x00000400n32,IN_ON_READ_EVENT=0x00000800n32,IN_ON_WRITE_EVENT=0x00001000n32,CONNECTING=0x00002000n32,CONNECTED=0x00004000n32,READING=0x00008000n32, andWRITING=0x00010000n32. connectcreates a socket and startsConnectEx.setConnectionis the handoff used by windows/TcpAcceptor after an accepted socket has completed.ConnectExis an exportedFN_CONNECTEXRefslot.connectresolves it throughWSAIoctlwhen it is nil.- The module uses the completion port exported by
windows/dispatcher; it does not create a fiber or a worker thread. DIEatomically enters its destruction state and asserts that the state was zero. Active connect/read/write operations and connected handles must be completed, canceled, or disconnected before destruction.
Methods
isConnected
(-- connected) Reports whether the atomic state contains CONNECTED; result connected is Cond.setConnection
(connection --) Installs one connected socket handle, initializes both dispatcher contexts, and stores CONNECTED. connection is a raw Natx handle supplied by the acceptor handoff.Use
- This is the cross-module handoff called by windows/TcpAcceptor after successful
AcceptExcompletion.
connect
(address port onConnect -- result) Starts one asynchronous ConnectEx. address is host-order Nat32, port is host-order Nat16, onConnect is a Function with source signature ({result: String Ref;} {} {}) Function, and result is the immediate String initiation result.Postconditions
- Success binds a local wildcard address, associates the socket with the dispatcher completion port, stores the callback, sets
CONNECTING, and returns an empty string. Completion invokes the callback and changes the state to connected or zero.
cancelConnect
(-- isCanceled) Attempts to cancel a pending ConnectEx with CancelIoEx; returns isCanceled: Cond.- The source may post a completion-port entry again if the connect callback raced with cancellation.
disconnect
(--) Closes the owned connected socket and stores the zero state.Preconditions
- The state is
CONNECTED; pending read or write operations must not remain active.
read
(data onRead -- result) Starts one overlapped receive into mutable data: Nat8 Span. onRead is a Function with source signature ({result: String Ref; numberOfTransferredBytes: Int32;} {} {}) Function; result is the immediate initiation result.Preconditions
- The state is
CONNECTED;dataconverts to a mutableNat8 Span; no read is already active.
cancelRead
(-- isCanceled) Attempts to cancel the active receive with CancelIoEx; returns isCanceled: Cond.write
(data onWrite -- result) Starts one overlapped send from data: Nat8 Cref Span. onWrite is a Function with source signature ({result: String Ref;} {} {}) Function; result is the immediate initiation result.Preconditions
- The state is
CONNECTED;dataconverts to a read-onlyNat8 Cref Span; no write is already active.
cancelWrite
(-- isCanceled) Attempts to cancel the active send with CancelIoEx; returns isCanceled: Cond.Completion and callback model
connect,read, andwritereturn before completion. Their callback fields are stored inFunctionobjects and are called by dispatcher completion handlers.- The read and write contexts embed one
OVERLAPPEDeach, storeselfas their context, and install the source's read or write event wrapper. The completion key is zero for these overlapped socket entries. - Connect completion checks
WSAGetOverlappedResult, updates the socket withSO_UPDATE_CONNECT_CONTEXT, and then marks the objectCONNECTED. The connect callback is stored in the write callback slot. - Read completion passes the transferred byte count as
Int32and a result reference toonRead. Write completion passes a result reference toonWrite. ERROR_OPERATION_ABORTEDbecomes result"canceled". Other completion errors are reported as"ConnectEx failed, result=","WSARecv failed, result=", or"WSASend failed, result="followed by the error code.- This differs from
sync/TcpConnection: the sync variant uses fibers, itsreadreturns a byte count directly, and it providesreadString; this module returns initiation strings and reports completion through callbacks. - Dispatch until the operation's completion callback has run before leaving the connection's scope. An empty immediate result means initiation succeeded, not completion; call
disconnectonly after successful completion has made the stateCONNECTED.
Ownership and threading
- The object owns
connection: Natxafter successfulconnectcompletion orsetConnection.disconnectcloses that handle. setConnectionis the accepted-socket handoff; the acceptor must not close the handle after handing it to the connection object.- State transitions use the source's acquire/release atomic operations. Invalid concurrent or out-of-order calls trigger the source assertions.
- The module creates no fiber and no worker thread. The thread that calls
dispatcher.dispatchordispatcher.tryDispatchruns the completion callback. - The source warns that callers must synchronize cancellation with the return from
connect,read, orwrite. The connect cancellation path also handles a callback race by reposting completion.
Results and errors
connectreports immediate setup errors beginning withsocket failed, result=,setsockopt failed, result=,bind failed, result=,WSAIoctl failed, result=,CreateIoCompletionPort failed, result=, orConnectEx failed, result=.readreports immediate receive errors asWSARecv failed, result=;writereports immediate send errors asWSASend failed, result=.- Cancellation returns
FALSEwhen no matching operation is active or whenCancelIoExfails. A failed cancellation other thanERROR_NOT_FOUNDis printed as a diagnostic. - A failed
closesocketprints aLEAK: closesocket failed, result=diagnostic. Invalid state and invalid span/callback forms use the source assertions or static argument error.
Examples
Windows dispatcher connection
"Function" use
"String" use
"control" use
"windows/TcpConnection" use
"windows/dispatcher" use
{} Int32 {} [
connection: TcpConnection;
handled: FALSE dynamic;
onConnect: ({result: String Ref;} {} {}) Function;
callback: [result:;];
@callback @onConnect.assign
result: 0x7F000001n32 6615n16 @onConnect @connection.connect;
[result.size 0 =] "connect failed" ensure
[handled ~] [dispatcher.tryDispatch @handled set] while
[@connection.isConnected] "connect did not complete" ensure
@connection.disconnect
0
] "main" exportFunction
See also
- windows/dispatcher: Windows completion-port dispatcher and callback posting helpers.
- windows/TcpAcceptor: Windows completion-port TCP acceptor with asynchronous callbacks.
- sync/TcpConnection: Connected TCP stream with buffered read, string read, write, and shutdown operations.
- windows/ws2_32: Winsock2 declarations for sockets, overlapped I/O, and address-resolution helpers.