0
# UDP Networking
1
2
UDP client implementations for sending OSC messages and bundles with support for broadcast transmissions, timeout handling, message reception, and response dispatching. UDP provides low-latency communication suitable for real-time applications.
3
4
## Capabilities
5
6
### Simple UDP Client
7
8
High-level UDP client with message building helpers for quick OSC communication.
9
10
```python { .api }
11
class SimpleUDPClient:
12
"""UDP client with message building helpers."""
13
14
def __init__(self, address: str, port: int, allow_broadcast: bool = False):
15
"""Initialize UDP client.
16
17
Parameters:
18
- address: Target IP address or hostname
19
- port: Target UDP port number
20
- allow_broadcast: Enable broadcast transmissions
21
"""
22
23
def send_message(self, address: str, value: ArgValue):
24
"""Build and send OSC message.
25
26
Parameters:
27
- address: OSC address pattern string
28
- value: Single argument or list of arguments
29
"""
30
31
def get_messages(self, timeout: int = 30) -> Generator[OscMessage, None, None]:
32
"""Receive and parse OSC messages.
33
34
Parameters:
35
- timeout: Receive timeout in seconds
36
37
Yields:
38
OscMessage objects from received datagrams
39
40
Raises:
41
socket.timeout: If no data received within timeout
42
"""
43
```
44
45
### Basic UDP Client
46
47
Low-level UDP client for sending pre-built messages and bundles.
48
49
```python { .api }
50
class UDPClient:
51
"""Basic OSC UDP client for sending messages and bundles."""
52
53
def __init__(self, address: str, port: int, allow_broadcast: bool = False,
54
family: socket.AddressFamily = socket.AF_UNSPEC):
55
"""Initialize UDP client.
56
57
Parameters:
58
- address: Target IP address or hostname
59
- port: Target UDP port number
60
- allow_broadcast: Enable broadcast transmissions
61
- family: Address family (AF_INET, AF_INET6, AF_UNSPEC)
62
"""
63
64
def send(self, content: Union[OscMessage, OscBundle]):
65
"""Send OSC message or bundle.
66
67
Parameters:
68
- content: OscMessage or OscBundle to transmit
69
70
Raises:
71
OSError: If transmission fails
72
"""
73
74
def receive(self, timeout: int = 30) -> bytes:
75
"""Receive raw datagram bytes.
76
77
Parameters:
78
- timeout: Receive timeout in seconds
79
80
Returns:
81
Raw datagram bytes
82
83
Raises:
84
socket.timeout: If no data received within timeout
85
"""
86
```
87
88
### Dispatcher Client
89
90
UDP client with automatic response handling using dispatcher pattern for bidirectional communication.
91
92
```python { .api }
93
class DispatchClient:
94
"""UDP client with dispatcher for handling responses."""
95
96
dispatcher: Dispatcher # Class-level dispatcher instance
97
98
def __init__(self, address: str, port: int, allow_broadcast: bool = False):
99
"""Initialize dispatcher client.
100
101
Parameters:
102
- address: Target IP address or hostname
103
- port: Target UDP port number
104
- allow_broadcast: Enable broadcast transmissions
105
"""
106
107
def send_message(self, address: str, value: ArgValue):
108
"""Build and send OSC message.
109
110
Parameters:
111
- address: OSC address pattern string
112
- value: Single argument or list of arguments
113
"""
114
115
def handle_messages(self, timeout: int = 30):
116
"""Process received messages with dispatcher.
117
118
Parameters:
119
- timeout: Receive timeout in seconds
120
121
Processes incoming messages using the class dispatcher,
122
calling mapped handlers for matching addresses.
123
"""
124
```
125
126
## Usage Examples
127
128
### Basic Message Sending
129
130
```python
131
from pythonosc import udp_client
132
133
# Create simple client
134
client = udp_client.SimpleUDPClient("127.0.0.1", 5005)
135
136
# Send various message types
137
client.send_message("/filter", 0.75)
138
client.send_message("/volume", [0.8, 0.6]) # Stereo volume
139
client.send_message("/synth/freq", 440.0)
140
client.send_message("/trigger", True)
141
client.send_message("/reset", []) # No arguments
142
```
143
144
### Broadcast Communication
145
146
```python
147
from pythonosc import udp_client
148
149
# Enable broadcast for network-wide messages
150
broadcast_client = udp_client.SimpleUDPClient("255.255.255.255", 9000,
151
allow_broadcast=True)
152
broadcast_client.send_message("/sync/beat", [120, 4, 4]) # BPM, time signature
153
```
154
155
### Sending Pre-built Messages
156
157
```python
158
from pythonosc import udp_client
159
from pythonosc.osc_message_builder import OscMessageBuilder
160
from pythonosc.osc_bundle_builder import OscBundleBuilder, IMMEDIATELY
161
162
# Create client
163
client = udp_client.UDPClient("192.168.1.100", 8000)
164
165
# Send pre-built message
166
builder = OscMessageBuilder("/instrument/piano")
167
builder.add_arg(60) # MIDI note
168
builder.add_arg(127) # Velocity
169
builder.add_arg(1.5) # Duration
170
message = builder.build()
171
client.send(message)
172
173
# Send bundle
174
bundle_builder = OscBundleBuilder(IMMEDIATELY)
175
bundle_builder.add_content(OscMessageBuilder("/note/on").add_arg(60).build())
176
bundle_builder.add_content(OscMessageBuilder("/note/on").add_arg(64).build())
177
bundle = bundle_builder.build()
178
client.send(bundle)
179
```
180
181
### Receiving Messages
182
183
```python
184
from pythonosc import udp_client
185
import socket
186
187
# Create receiving client
188
receiver = udp_client.SimpleUDPClient("127.0.0.1", 5006)
189
190
try:
191
# Receive messages with timeout
192
for message in receiver.get_messages(timeout=10):
193
print(f"Received: {message.address} -> {message.params}")
194
except socket.timeout:
195
print("No messages received within timeout")
196
```
197
198
### Bidirectional Communication with Dispatcher
199
200
```python
201
from pythonosc import udp_client
202
from pythonosc.dispatcher import Dispatcher
203
204
# Set up response handlers
205
def handle_ack(address, *args):
206
print(f"Acknowledgment: {address} {args}")
207
208
def handle_error(address, *args):
209
print(f"Error response: {address} {args}")
210
211
# Configure class dispatcher
212
DispatchClient.dispatcher = Dispatcher()
213
DispatchClient.dispatcher.map("/ack", handle_ack)
214
DispatchClient.dispatcher.map("/error", handle_error)
215
216
# Create dispatcher client
217
client = udp_client.DispatchClient("127.0.0.1", 5005)
218
219
# Send message and handle responses
220
client.send_message("/request/data", ["sensor1", "temperature"])
221
222
# Process responses
223
try:
224
client.handle_messages(timeout=5)
225
except socket.timeout:
226
print("No response received")
227
```
228
229
### IPv6 Support
230
231
```python
232
from pythonosc import udp_client
233
import socket
234
235
# IPv6 client
236
ipv6_client = udp_client.UDPClient("::1", 5005, family=socket.AF_INET6)
237
ipv6_client.send_message("/ipv6/test", "Hello IPv6")
238
239
# Auto-detect family
240
auto_client = udp_client.UDPClient("localhost", 5005, family=socket.AF_UNSPEC)
241
auto_client.send_message("/auto/detect", "Hello")
242
```
243
244
### Raw Datagram Handling
245
246
```python
247
from pythonosc import udp_client
248
from pythonosc.osc_message import OscMessage
249
from pythonosc.osc_bundle import OscBundle
250
251
# Low-level client
252
client = udp_client.UDPClient("127.0.0.1", 5005)
253
254
# Receive and parse manually
255
try:
256
raw_data = client.receive(timeout=30)
257
258
if OscMessage.dgram_is_message(raw_data):
259
message = OscMessage(raw_data)
260
print(f"Message: {message.address} {message.params}")
261
elif OscBundle.dgram_is_bundle(raw_data):
262
bundle = OscBundle(raw_data)
263
print(f"Bundle: {bundle.num_contents} items at {bundle.timestamp}")
264
265
except socket.timeout:
266
print("Receive timeout")
267
```
268
269
## Network Configuration Examples
270
271
### Multi-interface Setup
272
273
```python
274
from pythonosc import udp_client
275
import socket
276
277
# Bind to specific interface on multi-homed systems
278
interfaces = {
279
"local": udp_client.SimpleUDPClient("127.0.0.1", 5005),
280
"lan": udp_client.SimpleUDPClient("192.168.1.100", 5005),
281
"wan": udp_client.SimpleUDPClient("203.0.113.10", 5005)
282
}
283
284
# Send to different networks
285
interfaces["local"].send_message("/local/test", "localhost")
286
interfaces["lan"].send_message("/lan/broadcast", "network")
287
interfaces["wan"].send_message("/wan/remote", "internet")
288
```
289
290
### Performance Tuning
291
292
```python
293
from pythonosc import udp_client
294
import socket
295
296
# Create client with socket options
297
client = udp_client.UDPClient("127.0.0.1", 5005)
298
299
# Access underlying socket for tuning (if needed)
300
# Note: This requires accessing private attributes and should be used carefully
301
sock = client._sock
302
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 65536) # Send buffer
303
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536) # Receive buffer
304
```
305
306
## Types and Imports
307
308
```python { .api }
309
from typing import Union, Generator
310
import socket
311
312
from pythonosc.osc_message import OscMessage
313
from pythonosc.osc_bundle import OscBundle
314
from pythonosc.osc_message_builder import ArgValue
315
from pythonosc.dispatcher import Dispatcher
316
```