or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

asgi-middleware.mdasync-client.mdasync-server.mdclient.mdexceptions.mdindex.mdserver.mdwsgi-middleware.md

async-server.mddocs/

0

# Asynchronous Server

1

2

Engine.IO server optimized for asyncio-based applications with full async/await support. Provides the same functionality as the synchronous server but with coroutine-based methods for seamless integration with modern async web frameworks.

3

4

## Capabilities

5

6

### Server Initialization

7

8

Create and configure an asynchronous Engine.IO server with the same configuration options as the synchronous server.

9

10

```python { .api }

11

class AsyncServer:

12

def __init__(

13

self,

14

async_mode=None,

15

ping_interval=25,

16

ping_timeout=20,

17

max_http_buffer_size=1000000,

18

allow_upgrades=True,

19

http_compression=True,

20

compression_threshold=1024,

21

cookie=None,

22

cors_allowed_origins=None,

23

cors_credentials=True,

24

logger=False,

25

json=None,

26

async_handlers=True,

27

monitor_clients=None,

28

transports=None,

29

**kwargs

30

):

31

"""

32

Initialize asynchronous Engine.IO server.

33

34

Args:

35

async_mode (str, optional): Async mode for asyncio ('aiohttp', 'sanic', 'tornado', 'asgi')

36

ping_interval (int|tuple): Ping interval in seconds, default 25

37

ping_timeout (int): Ping timeout in seconds, default 20

38

max_http_buffer_size (int): Max message size in bytes, default 1,000,000

39

allow_upgrades (bool): Allow transport upgrades, default True

40

http_compression (bool): Enable HTTP compression, default True

41

compression_threshold (int): Compression threshold in bytes, default 1024

42

cookie (str|dict|None): Cookie configuration

43

cors_allowed_origins (str|list|callable): CORS allowed origins

44

cors_credentials (bool): Allow credentials in CORS, default True

45

logger (bool|Logger): Logging configuration, default False

46

json (module): Alternative JSON module

47

async_handlers (bool): Run handlers asynchronously, default True

48

monitor_clients (bool): Monitor client connections, default True

49

transports (list): Allowed transports, default ['polling', 'websocket']

50

"""

51

```

52

53

### Async Message Communication

54

55

Send messages and packets to connected clients using async/await syntax.

56

57

```python { .api }

58

async def send(self, sid, data):

59

"""

60

Send a message to a client (coroutine).

61

62

Args:

63

sid (str): Session ID of the client

64

data (any): Message data to send

65

66

Raises:

67

SocketIsClosedError: If client socket is closed

68

"""

69

70

async def send_packet(self, sid, pkt):

71

"""

72

Send a raw packet to a client (coroutine).

73

74

Args:

75

sid (str): Session ID of the client

76

pkt (Packet): Raw packet object to send

77

78

Raises:

79

SocketIsClosedError: If client socket is closed

80

"""

81

```

82

83

### Async Session Management

84

85

Manage client sessions asynchronously with coroutine-based methods.

86

87

```python { .api }

88

async def get_session(self, sid):

89

"""

90

Return the user session for a client (coroutine).

91

92

Args:

93

sid (str): Session ID of the client

94

95

Returns:

96

dict: User session data

97

98

Raises:

99

KeyError: If session does not exist

100

"""

101

102

async def save_session(self, sid, session):

103

"""

104

Store the user session for a client (coroutine).

105

106

Args:

107

sid (str): Session ID of the client

108

session (dict): Session data to store

109

"""

110

111

def session(self, sid):

112

"""

113

Return user session with async context manager syntax.

114

115

Args:

116

sid (str): Session ID of the client

117

118

Returns:

119

AsyncContextManager: Async session context manager for automatic save

120

"""

121

```

122

123

Usage example:

124

125

```python

126

# Direct async session management

127

session_data = await eio.get_session(sid)

128

session_data['user_id'] = 123

129

await eio.save_session(sid, session_data)

130

131

# Async context manager approach

132

async with eio.session(sid) as session:

133

session['user_id'] = 123

134

session['preferences'] = {'theme': 'dark'}

135

```

136

137

### Async Connection Management

138

139

Handle client connections and disconnections asynchronously.

140

141

```python { .api }

142

async def disconnect(self, sid=None):

143

"""

144

Disconnect a client or all clients (coroutine).

145

146

Args:

147

sid (str, optional): Session ID to disconnect. If None, disconnects all clients

148

"""

149

```

150

151

### Event Handling

152

153

Register event handlers that can be either synchronous or asynchronous functions.

154

155

```python { .api }

156

def on(self, event, handler=None):

157

"""

158

Register an event handler (synchronous method).

159

160

Args:

161

event (str): Event name ('connect', 'message', 'disconnect')

162

handler (callable, optional): Event handler function (sync or async)

163

164

Returns:

165

callable: Decorator function if handler not provided

166

"""

167

```

168

169

Usage examples:

170

171

```python

172

# Async event handlers

173

@eio.on('connect')

174

async def on_connect(sid, environ):

175

print(f'Client {sid} connected')

176

177

@eio.on('message')

178

async def on_message(sid, data):

179

print(f'Received: {data}')

180

await eio.send(sid, f'Echo: {data}')

181

182

@eio.on('disconnect')

183

async def on_disconnect(sid):

184

print(f'Client {sid} disconnected')

185

186

# Synchronous handlers also work

187

@eio.on('connect')

188

def on_connect_sync(sid, environ):

189

print(f'Client {sid} connected (sync)')

190

```

191

192

### Async Request Handling

193

194

Handle HTTP requests asynchronously for integration with ASGI applications.

195

196

```python { .api }

197

async def handle_request(self, *args, **kwargs):

198

"""

199

Handle an HTTP request (coroutine).

200

201

Args:

202

*args: Request arguments (varies by framework)

203

**kwargs: Request keyword arguments (varies by framework)

204

205

Returns:

206

Response object appropriate for the framework

207

"""

208

```

209

210

### Application Integration

211

212

Attach the server to various async web frameworks.

213

214

```python { .api }

215

def attach(self, app, engineio_path='engine.io'):

216

"""

217

Attach the server to an application.

218

219

Args:

220

app: Application object (aiohttp, Sanic, etc.)

221

engineio_path (str): Engine.IO endpoint path, default 'engine.io'

222

"""

223

```

224

225

### Async Background Tasks

226

227

Manage background tasks using asyncio.

228

229

```python { .api }

230

def start_background_task(self, target, *args, **kwargs):

231

"""

232

Start a background task using asyncio.

233

234

Args:

235

target (callable): Async task function to run

236

*args: Arguments for the task function

237

**kwargs: Keyword arguments for the task function

238

239

Returns:

240

asyncio.Task: Asyncio task object

241

"""

242

243

async def sleep(self, seconds=0):

244

"""

245

Sleep using asyncio (coroutine).

246

247

Args:

248

seconds (float): Sleep duration in seconds

249

"""

250

251

async def shutdown(self):

252

"""

253

Stop all background tasks and clean up resources (coroutine).

254

"""

255

```

256

257

### Synchronous Utility Methods

258

259

Inherited synchronous methods from the base server class.

260

261

```python { .api }

262

def transport(self, sid):

263

"""

264

Return the transport name for a client.

265

266

Args:

267

sid (str): Session ID of the client

268

269

Returns:

270

str: Transport name ('polling' or 'websocket')

271

"""

272

273

def create_queue(self, *args, **kwargs):

274

"""

275

Create an asyncio queue object.

276

277

Returns:

278

asyncio.Queue: Asyncio queue object

279

"""

280

281

def get_queue_empty_exception(self):

282

"""

283

Return the asyncio queue empty exception.

284

285

Returns:

286

asyncio.QueueEmpty: Asyncio queue empty exception

287

"""

288

289

def create_event(self, *args, **kwargs):

290

"""

291

Create an asyncio event object.

292

293

Returns:

294

asyncio.Event: Asyncio event object

295

"""

296

297

def generate_id(self):

298

"""

299

Generate a unique session ID.

300

301

Returns:

302

str: Unique session identifier

303

"""

304

```

305

306

### AsyncServer-specific Methods

307

308

Methods specific to the async server implementation.

309

310

```python { .api }

311

def is_asyncio_based(self):

312

"""

313

Return True to identify as asyncio-based server.

314

315

Returns:

316

bool: Always True for AsyncServer

317

"""

318

319

def async_modes(self):

320

"""

321

Return supported async modes for asyncio.

322

323

Returns:

324

list: ['aiohttp', 'sanic', 'tornado', 'asgi']

325

"""

326

```

327

328

## Server Lifecycle Events

329

330

The async server supports the same events as the synchronous server, but handlers can be async:

331

332

- **connect**: Fired when a client establishes a connection

333

- Handler signature: `async (sid: str, environ: dict) -> None` or `(sid: str, environ: dict) -> None`

334

335

- **message**: Fired when a message is received from a client

336

- Handler signature: `async (sid: str, data: any) -> None` or `(sid: str, data: any) -> None`

337

338

- **disconnect**: Fired when a client disconnects

339

- Handler signature: `async (sid: str) -> None` or `(sid: str) -> None`

340

341

## Framework Integration Examples

342

343

### FastAPI Integration

344

345

```python

346

import engineio

347

from fastapi import FastAPI

348

349

# Create async server

350

eio = engineio.AsyncServer(async_mode='asgi')

351

352

@eio.on('connect')

353

async def connect(sid, environ):

354

print(f'Client {sid} connected')

355

356

# Create ASGI app

357

app = engineio.ASGIApp(eio)

358

359

# Wrap with FastAPI

360

fastapi_app = FastAPI()

361

fastapi_app.mount("/", app)

362

```

363

364

### aiohttp Integration

365

366

```python

367

import engineio

368

from aiohttp import web

369

370

# Create async server

371

eio = engineio.AsyncServer(async_mode='aiohttp')

372

373

@eio.on('connect')

374

async def connect(sid, environ):

375

print(f'Client {sid} connected')

376

377

# Create aiohttp app

378

app = web.Application()

379

eio.attach(app)

380

```

381

382

## Error Handling

383

384

The async server may raise the same exceptions as the synchronous server:

385

386

- `EngineIOError`: Base exception for all Engine.IO errors

387

- `SocketIsClosedError`: When attempting to send to a closed socket

388

- `ContentTooLongError`: When message size exceeds buffer limits

389

- `ConnectionError`: When connection fails or is lost unexpectedly