or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

asyncio.mdindex.mdtwisted.mdutilities.mdwamp.mdwebsocket.md

index.mddocs/

0

# Autobahn

1

2

Autobahn|Python is a comprehensive WebSocket and WAMP (Web Application Messaging Protocol) implementation that provides both client and server capabilities for real-time bidirectional communication. It supports asynchronous Remote Procedure Calls and Publish & Subscribe messaging patterns, running on both Twisted and asyncio frameworks with high-performance native extensions.

3

4

## Package Information

5

6

- **Package Name**: autobahn

7

- **Language**: Python

8

- **Installation**: `pip install autobahn`

9

10

## Core Imports

11

12

```python

13

import autobahn

14

```

15

16

Framework-specific imports:

17

18

```python

19

# For asyncio applications

20

from autobahn.asyncio.websocket import WebSocketServerProtocol, WebSocketClientProtocol, WebSocketServerFactory, WebSocketClientFactory

21

from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner

22

23

# For Twisted applications

24

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketClientProtocol, WebSocketServerFactory, WebSocketClientFactory

25

from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner

26

27

# Core WAMP functionality

28

from autobahn.wamp import ApplicationSession, register, subscribe

29

from autobahn.wamp.types import ComponentConfig

30

```

31

32

## Basic Usage

33

34

### WebSocket Server (asyncio)

35

36

```python

37

import asyncio

38

from autobahn.asyncio.websocket import WebSocketServerProtocol, WebSocketServerFactory

39

40

class MyServerProtocol(WebSocketServerProtocol):

41

def onConnect(self, request):

42

print(f"Client connecting: {request.peer}")

43

44

def onOpen(self):

45

print("WebSocket connection open.")

46

47

def onMessage(self, payload, isBinary):

48

if isBinary:

49

print(f"Binary message of {len(payload)} bytes received.")

50

else:

51

print(f"Text message received: {payload.decode('utf8')}")

52

53

# Echo back the message

54

self.sendMessage(payload, isBinary)

55

56

def onClose(self, wasClean, code, reason):

57

print(f"WebSocket connection closed: {reason}")

58

59

# Create factory and run server

60

factory = WebSocketServerFactory("ws://localhost:9000")

61

factory.protocol = MyServerProtocol

62

63

loop = asyncio.get_event_loop()

64

coro = loop.create_server(factory, '0.0.0.0', 9000)

65

server = loop.run_until_complete(coro)

66

loop.run_forever()

67

```

68

69

### WAMP Application Session

70

71

```python

72

import asyncio

73

from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner

74

from autobahn.wamp import register, subscribe

75

76

class MyComponent(ApplicationSession):

77

async def onJoin(self, details):

78

print("Session ready")

79

80

# Register a procedure

81

await self.register(self.add2, 'com.myapp.add2')

82

83

# Subscribe to a topic

84

await self.subscribe(self.on_event, 'com.myapp.hello')

85

86

@register('com.myapp.add2')

87

async def add2(self, x, y):

88

return x + y

89

90

@subscribe('com.myapp.hello')

91

async def on_event(self, msg):

92

print(f"Got event: {msg}")

93

94

# Run the component

95

runner = ApplicationRunner(url="ws://localhost:8080/ws", realm="realm1")

96

runner.run(MyComponent)

97

```

98

99

## Architecture

100

101

Autobahn|Python is built around several key architectural components:

102

103

- **Framework Abstraction**: Uses txaio to provide unified async/await patterns across Twisted and asyncio

104

- **Transport Layer**: Supports WebSocket (RFC 6455) and RawSocket transports with full protocol compliance

105

- **WAMP Protocol**: Implements Web Application Messaging Protocol for RPC and PubSub over WebSocket

106

- **Native Extensions**: High-performance UTF-8 validation and cryptographic operations through NVX

107

- **Modular Design**: Cleanly separated WebSocket, WAMP, framework-specific, and optional XBR components

108

109

Framework selection is automatic based on imports or can be controlled via environment variables (`USE_TWISTED`, `USE_ASYNCIO`).

110

111

## Capabilities

112

113

### WebSocket Protocol Implementation

114

115

Complete RFC 6455 WebSocket implementation with client and server support, message compression, frame-level API, streaming capabilities, and extensive protocol options.

116

117

```python { .api }

118

class WebSocketServerProtocol:

119

def onConnect(self, request: ConnectionRequest) -> None: ...

120

def onOpen(self) -> None: ...

121

def sendMessage(self, payload: bytes, isBinary: bool = False) -> None: ...

122

def onMessage(self, payload: bytes, isBinary: bool) -> None: ...

123

def onClose(self, wasClean: bool, code: int, reason: str) -> None: ...

124

125

class WebSocketClientProtocol:

126

def onConnect(self, response: ConnectionResponse) -> None: ...

127

def onOpen(self) -> None: ...

128

def sendMessage(self, payload: bytes, isBinary: bool = False) -> None: ...

129

def onMessage(self, payload: bytes, isBinary: bool) -> None: ...

130

def onClose(self, wasClean: bool, code: int, reason: str) -> None: ...

131

132

class WebSocketServerFactory:

133

def __init__(self, url: str = None, protocols: list = None): ...

134

protocol: WebSocketServerProtocol

135

136

class WebSocketClientFactory:

137

def __init__(self, url: str = None, protocols: list = None): ...

138

protocol: WebSocketClientProtocol

139

```

140

141

[WebSocket Protocol](./websocket.md)

142

143

### WAMP Messaging Protocol

144

145

Web Application Messaging Protocol implementation providing Remote Procedure Calls (RPC) and Publish & Subscribe (PubSub) patterns with authentication, authorization, and advanced routing features.

146

147

```python { .api }

148

class ApplicationSession:

149

async def onJoin(self, details: SessionDetails) -> None: ...

150

async def call(self, procedure: str, *args, **kwargs) -> Any: ...

151

async def register(self, endpoint: callable, procedure: str) -> Registration: ...

152

async def publish(self, topic: str, *args, **kwargs) -> Publication: ...

153

async def subscribe(self, handler: callable, topic: str) -> Subscription: ...

154

155

class ApplicationRunner:

156

def __init__(self, url: str, realm: str = None, extra: dict = None,

157

serializers: list = None, ssl: bool = None, proxy: dict = None,

158

headers: dict = None): ...

159

def run(self, make: callable, start_loop: bool = True, log_level: str = 'info'): ...

160

161

def register(procedure: str, options: RegisterOptions = None): ...

162

def subscribe(topic: str, options: SubscribeOptions = None): ...

163

```

164

165

[WAMP Protocol](./wamp.md)

166

167

### Framework Integrations

168

169

Dedicated implementations for both Twisted and asyncio frameworks, providing native async/await support and framework-specific optimizations.

170

171

```python { .api }

172

# AsyncIO specific classes

173

class autobahn.asyncio.WebSocketServerProtocol: ...

174

class autobahn.asyncio.WebSocketClientProtocol: ...

175

class autobahn.asyncio.ApplicationSession: ...

176

177

# Twisted specific classes

178

class autobahn.twisted.WebSocketServerProtocol: ...

179

class autobahn.twisted.WebSocketClientProtocol: ...

180

class autobahn.twisted.ApplicationSession: ...

181

```

182

183

[AsyncIO Integration](./asyncio.md)

184

[Twisted Integration](./twisted.md)

185

186

### Utilities and Extensions

187

188

Core utilities, exception handling, native performance extensions, and optional blockchain integration through XBR protocol.

189

190

```python { .api }

191

# Core utilities

192

def generate_token() -> str: ...

193

def machine_id() -> str: ...

194

195

# Native extensions

196

class Utf8Validator: ...

197

198

# Exception handling

199

class ApplicationError(Error): ...

200

class TransportLost(Exception): ...

201

```

202

203

[Utilities](./utilities.md)

204

205

## Types

206

207

### Core Configuration Types

208

209

```python { .api }

210

class ComponentConfig:

211

def __init__(self, realm: str, extra: dict = None, keyring: IKeyRing = None): ...

212

213

class SessionDetails:

214

realm: str

215

session: int

216

authid: str

217

authrole: str

218

authmethod: str

219

220

class TransportDetails:

221

peer: str

222

is_secure: bool

223

channel_type: str

224

```

225

226

### WebSocket Message Types

227

228

```python { .api }

229

class ConnectionRequest:

230

peer: str

231

headers: dict

232

host: str

233

path: str

234

params: dict

235

version: int

236

origin: str

237

protocols: list

238

extensions: list

239

240

class ConnectionResponse:

241

peer: str

242

headers: dict

243

version: int

244

protocol: str

245

extensions: list

246

247

class Message:

248

payload: bytes

249

is_binary: bool

250

```

251

252

### WAMP Operation Types

253

254

```python { .api }

255

class CallOptions:

256

timeout: float = None

257

receive_progress: bool = None

258

disclose_me: bool = None

259

260

class RegisterOptions:

261

match: str = None

262

invoke: str = None

263

concurrency: int = None

264

disclose_caller: bool = None

265

266

class SubscribeOptions:

267

match: str = None

268

get_retained: bool = None

269

270

class PublishOptions:

271

acknowledge: bool = None

272

exclude_me: bool = None

273

exclude: list = None

274

exclude_authid: list = None

275

exclude_authrole: list = None

276

eligible: list = None

277

eligible_authid: list = None

278

eligible_authrole: list = None

279

retain: bool = None

280

```

281

282

### Error Types

283

284

```python { .api }

285

class Error(Exception):

286

def __init__(self, error_uri: str, args: list = None, kwargs: dict = None): ...

287

288

class ApplicationError(Error): ...

289

class InvalidUri(Error): ...

290

class SerializationError(Error): ...

291

class ProtocolError(Error): ...

292

class TransportLost(Exception): ...

293

class SessionNotReady(Exception): ...

294

class PayloadExceededError(RuntimeError): ...

295

class Disconnected(RuntimeError): ...

296

```