Back to Message Handlers (.z Namespace)

Interprocess Communication (IPC) · Message Handlers (.z Namespace) · Practice Question

Detect When a Connection Has Closed

Sign in to track your progress

Question

How can a server detect when a connected client has closed its connection or gone away?

Solution

Override .z.pc on the server:

/ Server
\p 1234
.z.pc:{[handle] show "Disconnect on handle ",string handle}
/ Client
h:hopen `:localhost:1234:jeremy:password
hclose h

When hclose runs on the client, the server prints:

"Disconnect on handle 4"

Explanation

.z.pc fires once whenever a connection closes — whether the client called hclose, the client process died, or the network dropped. The argument is the handle that just closed.

Because the handle is passed in directly, .z.pc is the natural place to clean up any per-connection state the server was maintaining — for example, removing the handle from a session registry that was populated when .z.po fired:

sessions:([]handle:`int$(); username:`symbol$(); ipaddr:`int$())

.z.po:{
  `sessions insert (.z.w; .z.u; .z.a)
 }

.z.pc:{[h]
  delete from `sessions where handle=h
 }

Note that .z.pc receives the closing handle as its argument, not via .z.w — by the time it fires, the connection is already gone and .z.w is no longer meaningful for it.