0
# Constants
1
2
Comprehensive constants for socket types, options, events, and error codes, organized as Python enums for type safety and IDE support.
3
4
## Capabilities
5
6
### Socket Types
7
8
ZMQ socket type constants defining communication patterns.
9
10
```python { .api }
11
class SocketType(IntEnum):
12
"""ZMQ socket types for different messaging patterns"""
13
14
# Basic socket types
15
PAIR: int # Exclusive pair pattern
16
PUB: int # Publisher socket
17
SUB: int # Subscriber socket
18
REQ: int # Request socket (client)
19
REP: int # Reply socket (server)
20
DEALER: int # Dealer socket (async REQ)
21
ROUTER: int # Router socket (async REP)
22
PULL: int # Pull socket (worker)
23
PUSH: int # Push socket (ventilator)
24
XPUB: int # Extended publisher
25
XSUB: int # Extended subscriber
26
STREAM: int # Stream socket for TCP
27
28
# Deprecated aliases
29
XREQ: int # Deprecated alias for DEALER
30
XREP: int # Deprecated alias for ROUTER
31
32
# Draft socket types (experimental)
33
SERVER: int # Server socket
34
CLIENT: int # Client socket
35
RADIO: int # Radio socket
36
DISH: int # Dish socket
37
GATHER: int # Gather socket
38
SCATTER: int # Scatter socket
39
DGRAM: int # Datagram socket
40
PEER: int # Peer socket
41
CHANNEL: int # Channel socket
42
```
43
44
### Socket Options
45
46
Extensive socket configuration options for controlling behavior and performance.
47
48
```python { .api }
49
class SocketOption(IntEnum):
50
"""Socket configuration options"""
51
52
# Connection and identity
53
AFFINITY: int # I/O thread affinity
54
ROUTING_ID: int # Socket routing ID
55
SUBSCRIBE: int # Subscription filter (SUB)
56
UNSUBSCRIBE: int # Remove subscription (SUB)
57
RATE: int # Multicast data rate
58
RECOVERY_IVL: int # Multicast recovery interval
59
SNDBUF: int # Send buffer size
60
RCVBUF: int # Receive buffer size
61
RCVMORE: int # More message parts available
62
63
# Flow control
64
RCVHWM: int # Receive high water mark
65
SNDHWM: int # Send high water mark
66
HWM: int # High water mark (both)
67
68
# Timeouts and intervals
69
LINGER: int # Socket linger period
70
RECONNECT_IVL: int # Reconnection interval
71
RECONNECT_IVL_MAX: int # Maximum reconnection interval
72
BACKLOG: int # Listen backlog
73
MAXMSGSIZE: int # Maximum message size
74
75
# Socket state
76
FD: int # Socket file descriptor
77
EVENTS: int # Socket event state
78
TYPE: int # Socket type
79
RCVTIMEO: int # Receive timeout
80
SNDTIMEO: int # Send timeout
81
82
# Protocol options
83
IPV6: int # IPv6 socket option
84
IPV4ONLY: int # IPv4-only socket
85
IMMEDIATE: int # Queue messages only for completed connections
86
DELAY_ATTACH_ON_CONNECT: int # Delay connection completion
87
88
# Security and authentication
89
PLAIN_SERVER: int # PLAIN security server
90
PLAIN_USERNAME: int # PLAIN username
91
PLAIN_PASSWORD: int # PLAIN password
92
CURVE_SERVER: int # CURVE security server
93
CURVE_PUBLICKEY: int # CURVE public key
94
CURVE_SECRETKEY: int # CURVE secret key
95
CURVE_SERVERKEY: int # CURVE server key
96
ZAP_DOMAIN: int # ZAP authentication domain
97
98
# Advanced options
99
TCP_KEEPALIVE: int # TCP keepalive
100
TCP_KEEPALIVE_CNT: int # TCP keepalive count
101
TCP_KEEPALIVE_IDLE: int # TCP keepalive idle
102
TCP_KEEPALIVE_INTVL: int # TCP keepalive interval
103
TCP_ACCEPT_FILTER: int # TCP accept filter
104
105
# Monitoring and debugging
106
MONITOR: int # Socket monitoring
107
LAST_ENDPOINT: int # Last bound/connected endpoint
108
ROUTER_MANDATORY: int # Router mandatory routing
109
ROUTER_RAW: int # Router raw mode
110
PROBE_ROUTER: int # Probe router connections
111
REQ_CORRELATE: int # REQ correlation
112
REQ_RELAXED: int # REQ relaxed mode
113
114
# Multicast options
115
MULTICAST_HOPS: int # Multicast hop limit
116
MULTICAST_MAXTPDU: int # Maximum transport data unit
117
118
# Performance options
119
USE_FD: int # Use file descriptor
120
ROUTER_HANDOVER: int # Router handover
121
TOS: int # Type of service
122
ROUTER_NOTIFY: int # Router notifications
123
BINDTODEVICE: int # Bind to device
124
GSSAPI_SERVER: int # GSSAPI server mode
125
GSSAPI_PLAINTEXT: int # GSSAPI plaintext mode
126
```
127
128
### Context Options
129
130
Options for configuring ZMQ contexts.
131
132
```python { .api }
133
class ContextOption(IntEnum):
134
"""Context configuration options"""
135
136
IO_THREADS: int # Number of I/O threads
137
MAX_SOCKETS: int # Maximum sockets per context
138
SOCKET_LIMIT: int # Socket limit
139
THREAD_PRIORITY: int # Thread priority
140
THREAD_SCHED_POLICY: int # Thread scheduling policy
141
MAX_MSGSZ: int # Maximum message size
142
MSG_T_SIZE: int # Message structure size
143
THREAD_AFFINITY_CPU_ADD: int # Add CPU affinity
144
THREAD_AFFINITY_CPU_REMOVE: int # Remove CPU affinity
145
THREAD_NAME_PREFIX: int # Thread name prefix
146
```
147
148
### Event Types
149
150
Constants for socket monitoring and event handling.
151
152
```python { .api }
153
class Event(IntEnum):
154
"""Socket event types for monitoring"""
155
156
CONNECTED: int # Socket connected
157
CONNECT_DELAYED: int # Connection delayed
158
CONNECT_RETRIED: int # Connection retried
159
LISTENING: int # Socket listening
160
BIND_FAILED: int # Bind failed
161
ACCEPTED: int # Connection accepted
162
ACCEPT_FAILED: int # Accept failed
163
CLOSED: int # Socket closed
164
CLOSE_FAILED: int # Close failed
165
DISCONNECTED: int # Socket disconnected
166
MONITOR_STOPPED: int # Monitoring stopped
167
HANDSHAKE_FAILED_NO_DETAIL: int # Handshake failed
168
HANDSHAKE_SUCCEEDED: int # Handshake succeeded
169
HANDSHAKE_FAILED_PROTOCOL: int # Protocol handshake failed
170
HANDSHAKE_FAILED_AUTH: int # Auth handshake failed
171
172
# Event aggregates
173
ALL: int # All events
174
```
175
176
### Poll Events
177
178
Constants for polling socket events.
179
180
```python { .api }
181
class PollEvent(IntEnum):
182
"""Socket polling event flags"""
183
184
POLLIN: int # Socket readable
185
POLLOUT: int # Socket writable
186
POLLERR: int # Socket error
187
```
188
189
### Message Options
190
191
Options for message handling and properties.
192
193
```python { .api }
194
class MessageOption(IntEnum):
195
"""Message property constants"""
196
197
MORE: int # More message parts follow
198
SRCFD: int # Source file descriptor
199
SHARED: int # Message is shared
200
PROBE_ROUTER: int # Probe router message
201
ROUTING_ID: int # Message routing ID
202
GROUP: int # Message group
203
```
204
205
### Error Codes
206
207
ZMQ-specific error codes extending standard errno values.
208
209
```python { .api }
210
class Errno(IntEnum):
211
"""ZMQ error codes"""
212
213
# Standard errno values
214
EAGAIN: int # Resource temporarily unavailable
215
EFAULT: int # Bad address
216
EINVAL: int # Invalid argument
217
EMSGSIZE: int # Message too long
218
ENOTSUP: int # Operation not supported
219
EPROTONOSUPPORT: int # Protocol not supported
220
ENOBUFS: int # No buffer space available
221
ENETDOWN: int # Network is down
222
EADDRINUSE: int # Address already in use
223
EADDRNOTAVAIL: int # Cannot assign requested address
224
ECONNREFUSED: int # Connection refused
225
EINPROGRESS: int # Operation now in progress
226
ENOTSOCK: int # Socket operation on non-socket
227
EAFNOSUPPORT: int # Address family not supported
228
ENETUNREACH: int # Network is unreachable
229
ECONNABORTED: int # Software caused connection abort
230
ECONNRESET: int # Connection reset by peer
231
ENOTCONN: int # Transport endpoint is not connected
232
ETIMEDOUT: int # Connection timed out
233
EHOSTUNREACH: int # No route to host
234
ENETRESET: int # Network dropped connection because of reset
235
236
# ZMQ-specific errors
237
EFSM: int # Operation cannot be accomplished in current state
238
ENOCOMPATPROTO: int # The protocol is not compatible with the socket type
239
ETERM: int # Context was terminated
240
EMTHREAD: int # No I/O thread available
241
```
242
243
### Device Types
244
245
Constants for ZMQ devices.
246
247
```python { .api }
248
class DeviceType(IntEnum):
249
"""Device type constants"""
250
251
QUEUE: int # Load-balancing queue device
252
FORWARDER: int # Message forwarder device
253
STREAMER: int # Message streamer device
254
```
255
256
### Security Mechanisms
257
258
Constants for security and authentication mechanisms.
259
260
```python { .api }
261
class SecurityMechanism(IntEnum):
262
"""Security mechanism constants"""
263
264
NULL: int # No security
265
PLAIN: int # Plain text authentication
266
CURVE: int # CURVE encryption
267
GSSAPI: int # GSSAPI authentication
268
```
269
270
### Additional Constants
271
272
Various other constants used throughout PyZMQ.
273
274
```python { .api }
275
class Flag(IntEnum):
276
"""Message and socket flags"""
277
278
NOBLOCK: int # Non-blocking operation
279
DONTWAIT: int # Alias for NOBLOCK
280
SNDMORE: int # Send more parts
281
```
282
283
### Version Information
284
285
Constants related to ZMQ version handling.
286
287
```python { .api }
288
# Version constants
289
VERSION_MAJOR: int # Major version number
290
VERSION_MINOR: int # Minor version number
291
VERSION_PATCH: int # Patch version number
292
VERSION: int # Combined version number
293
294
# Protocol versions
295
PROTOCOL_ERROR_ZMTP_V1: int # ZMTP 1.0 protocol error
296
PROTOCOL_ERROR_ZMTP_V3: int # ZMTP 3.0 protocol error
297
PROTOCOL_ERROR_ZAP_V1: int # ZAP 1.0 protocol error
298
```
299
300
## Usage Examples
301
302
### Socket Type Usage
303
304
```python
305
import zmq
306
307
context = zmq.Context()
308
309
# Use socket type constants
310
publisher = context.socket(zmq.PUB)
311
subscriber = context.socket(zmq.SUB)
312
requester = context.socket(zmq.REQ)
313
replier = context.socket(zmq.REP)
314
dealer = context.socket(zmq.DEALER)
315
router = context.socket(zmq.ROUTER)
316
317
# Clean up
318
for socket in [publisher, subscriber, requester, replier, dealer, router]:
319
socket.close()
320
context.term()
321
```
322
323
### Socket Options Configuration
324
325
```python
326
import zmq
327
328
context = zmq.Context()
329
socket = context.socket(zmq.PUB)
330
331
# Configure socket options
332
socket.setsockopt(zmq.SNDHWM, 1000) # Send high water mark
333
socket.setsockopt(zmq.RCVHWM, 1000) # Receive high water mark
334
socket.setsockopt(zmq.LINGER, 1000) # Linger period
335
socket.setsockopt(zmq.RCVTIMEO, 5000) # Receive timeout
336
socket.setsockopt(zmq.SNDTIMEO, 5000) # Send timeout
337
socket.setsockopt(zmq.SNDBUF, 65536) # Send buffer size
338
socket.setsockopt(zmq.RCVBUF, 65536) # Receive buffer size
339
340
# Read socket options
341
hwm = socket.getsockopt(zmq.SNDHWM)
342
socket_type = socket.getsockopt(zmq.TYPE)
343
events = socket.getsockopt(zmq.EVENTS)
344
345
print(f"Send HWM: {hwm}")
346
print(f"Socket type: {socket_type}")
347
print(f"Events: {events}")
348
349
socket.close()
350
context.term()
351
```
352
353
### Context Configuration
354
355
```python
356
import zmq
357
358
# Configure context options
359
context = zmq.Context()
360
context.set(zmq.IO_THREADS, 4) # 4 I/O threads
361
context.set(zmq.MAX_SOCKETS, 1024) # Max 1024 sockets
362
context.set(zmq.THREAD_PRIORITY, 1) # Thread priority
363
364
# Read context options
365
io_threads = context.get(zmq.IO_THREADS)
366
max_sockets = context.get(zmq.MAX_SOCKETS)
367
368
print(f"I/O threads: {io_threads}")
369
print(f"Max sockets: {max_sockets}")
370
371
context.term()
372
```
373
374
### Event Monitoring
375
376
```python
377
import zmq
378
379
context = zmq.Context()
380
socket = context.socket(zmq.REQ)
381
382
# Start monitoring all events
383
socket.monitor("inproc://monitor", zmq.EVENT_ALL)
384
385
# Or monitor specific events
386
socket.monitor("inproc://monitor",
387
zmq.EVENT_CONNECTED | zmq.EVENT_DISCONNECTED)
388
389
# Create monitor socket to receive events
390
monitor = context.socket(zmq.PAIR)
391
monitor.connect("inproc://monitor")
392
393
socket.connect("tcp://localhost:5555")
394
395
# Receive monitoring events
396
try:
397
event = monitor.recv_pyobj(zmq.NOBLOCK)
398
print(f"Event: {event}")
399
except zmq.Again:
400
print("No events")
401
402
socket.close()
403
monitor.close()
404
context.term()
405
```
406
407
### Polling with Event Constants
408
409
```python
410
import zmq
411
412
context = zmq.Context()
413
socket = context.socket(zmq.REQ)
414
socket.connect("tcp://localhost:5555")
415
416
poller = zmq.Poller()
417
poller.register(socket, zmq.POLLIN | zmq.POLLOUT)
418
419
# Poll for events
420
events = poller.poll(1000) # 1 second timeout
421
422
for sock, event in events:
423
if event & zmq.POLLIN:
424
print("Socket is readable")
425
if event & zmq.POLLOUT:
426
print("Socket is writable")
427
if event & zmq.POLLERR:
428
print("Socket has error")
429
430
socket.close()
431
context.term()
432
```
433
434
### Error Handling with Constants
435
436
```python
437
import zmq
438
439
context = zmq.Context()
440
socket = context.socket(zmq.REQ)
441
442
try:
443
# This will fail - no connection
444
socket.recv(zmq.NOBLOCK)
445
except zmq.ZMQError as e:
446
if e.errno == zmq.EAGAIN:
447
print("No message available (non-blocking)")
448
elif e.errno == zmq.EFSM:
449
print("Finite state machine error")
450
elif e.errno == zmq.ETERM:
451
print("Context was terminated")
452
else:
453
print(f"Other ZMQ error: {e}")
454
455
socket.close()
456
context.term()
457
```
458
459
### Security Configuration
460
461
```python
462
import zmq
463
464
context = zmq.Context()
465
server = context.socket(zmq.REP)
466
467
# Configure CURVE security
468
server.setsockopt(zmq.CURVE_SERVER, 1)
469
server.setsockopt(zmq.CURVE_SECRETKEY, server_secret_key)
470
471
# Configure PLAIN security
472
# server.setsockopt(zmq.PLAIN_SERVER, 1)
473
474
# Configure authentication domain
475
server.setsockopt_string(zmq.ZAP_DOMAIN, "global")
476
477
server.bind("tcp://*:5555")
478
479
# Client configuration
480
client = context.socket(zmq.REQ)
481
client.setsockopt(zmq.CURVE_PUBLICKEY, client_public_key)
482
client.setsockopt(zmq.CURVE_SECRETKEY, client_secret_key)
483
client.setsockopt(zmq.CURVE_SERVERKEY, server_public_key)
484
485
client.connect("tcp://localhost:5555")
486
487
server.close()
488
client.close()
489
context.term()
490
```
491
492
### Message Flags Usage
493
494
```python
495
import zmq
496
497
context = zmq.Context()
498
socket = context.socket(zmq.PUSH)
499
socket.bind("tcp://*:5555")
500
501
# Send multipart message
502
socket.send(b"Part 1", zmq.SNDMORE) # More parts follow
503
socket.send(b"Part 2", zmq.SNDMORE) # More parts follow
504
socket.send(b"Part 3") # Last part (no SNDMORE)
505
506
# Non-blocking send
507
try:
508
socket.send(b"Message", zmq.NOBLOCK)
509
except zmq.Again:
510
print("Send would block")
511
512
socket.close()
513
context.term()
514
```
515
516
### Version Checking
517
518
```python
519
import zmq
520
521
# Check PyZMQ version
522
print(f"PyZMQ version: {zmq.pyzmq_version()}")
523
524
# Check libzmq version
525
print(f"libzmq version: {zmq.zmq_version()}")
526
527
# Version info as tuple
528
zmq_version_info = zmq.zmq_version_info()
529
print(f"libzmq version info: {zmq_version_info}")
530
531
# Check for specific features
532
if zmq.has("curve"):
533
print("CURVE security available")
534
535
if zmq.has("ipc"):
536
print("IPC transport available")
537
538
if zmq.has("pgm"):
539
print("PGM multicast available")
540
```
541
542
### Device Constants
543
544
```python
545
import zmq
546
from zmq.devices import Device
547
548
context = zmq.Context()
549
550
frontend = context.socket(zmq.ROUTER)
551
frontend.bind("tcp://*:5559")
552
553
backend = context.socket(zmq.DEALER)
554
backend.bind("tcp://*:5560")
555
556
# Use device type constants
557
queue_device = Device(zmq.QUEUE, frontend, backend)
558
# forwarder_device = Device(zmq.FORWARDER, frontend, backend)
559
# streamer_device = Device(zmq.STREAMER, frontend, backend)
560
561
try:
562
queue_device.run()
563
except KeyboardInterrupt:
564
pass
565
finally:
566
frontend.close()
567
backend.close()
568
context.term()
569
```
570
571
## Enum Access Patterns
572
573
```python
574
import zmq
575
576
# Access constants directly
577
socket = context.socket(zmq.REQ)
578
socket.setsockopt(zmq.LINGER, 1000)
579
580
# Access through enum classes (type-safe)
581
from zmq.constants import SocketType, SocketOption
582
583
socket = context.socket(SocketType.REQ)
584
socket.setsockopt(SocketOption.LINGER, 1000)
585
586
# Check if constant exists
587
if hasattr(zmq, 'CURVE_SERVER'):
588
print("CURVE security available")
589
590
# Iterate over enum values
591
for socket_type in SocketType:
592
print(f"Socket type: {socket_type.name} = {socket_type.value}")
593
```
594
595
## Types
596
597
```python { .api }
598
from enum import IntEnum
599
from typing import Union
600
601
# Enum base types
602
ZMQConstant = int
603
ConstantValue = Union[int, str, bytes]
604
605
# Socket configuration types
606
SocketTypeValue = int # Socket type constant value
607
SocketOptionValue = int # Socket option constant value
608
ContextOptionValue = int # Context option constant value
609
EventValue = int # Event constant value
610
ErrorValue = int # Error code constant value
611
612
# Flag combinations
613
MessageFlags = int # Combination of message flags
614
PollFlags = int # Combination of poll flags
615
EventFlags = int # Combination of event flags
616
617
# Version types
618
VersionTuple = tuple[int, int, int] # (major, minor, patch)
619
VersionNumber = int # Combined version number
620
```