or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

clients.mdexceptions.mdindex.mdintegration.mdmanagers.mdnamespaces.mdservers.md

clients.mddocs/

0

# Client Classes

1

2

Socket.IO client implementations for connecting to servers and exchanging real-time messages. The library provides both simple clients for basic use cases and full-featured clients with advanced capabilities like automatic reconnection, namespace support, and event-driven architecture.

3

4

## Capabilities

5

6

### SimpleClient

7

8

A simple synchronous Socket.IO client that provides blocking methods for basic real-time communication. Ideal for simple scripts and straightforward client scenarios.

9

10

```python { .api }

11

class SimpleClient:

12

"""

13

Simple synchronous Socket.IO client with blocking methods.

14

15

Attributes:

16

sid (str): Session ID assigned by server

17

transport (str): Current transport method ('websocket' or 'polling')

18

"""

19

20

def connect(self, url, headers=None, auth=None, transports=None, wait_timeout=1):

21

"""

22

Connect to a Socket.IO server.

23

24

Args:

25

url (str): Server URL

26

headers (dict, optional): HTTP headers to send

27

auth (dict, optional): Authentication credentials

28

transports (list, optional): Allowed transport methods ['websocket', 'polling']

29

wait_timeout (int): Connection timeout in seconds

30

31

Raises:

32

ConnectionError: Failed to connect to server

33

"""

34

35

def emit(self, event, data=None):

36

"""

37

Emit an event to the server.

38

39

Args:

40

event (str): Event name

41

data: Event data to send

42

43

Raises:

44

DisconnectedError: Client not connected to server

45

"""

46

47

def call(self, event, data=None, timeout=60):

48

"""

49

Emit an event and wait for a response.

50

51

Args:

52

event (str): Event name

53

data: Event data to send

54

timeout (int): Response timeout in seconds

55

56

Returns:

57

Response data from server

58

59

Raises:

60

TimeoutError: No response received within timeout

61

DisconnectedError: Client not connected to server

62

"""

63

64

def receive(self, timeout=None):

65

"""

66

Wait for an event from the server.

67

68

Args:

69

timeout (int, optional): Receive timeout in seconds

70

71

Returns:

72

tuple: (event_name, event_data)

73

74

Raises:

75

TimeoutError: No event received within timeout

76

DisconnectedError: Client not connected to server

77

"""

78

79

def disconnect(self):

80

"""

81

Disconnect from the server.

82

"""

83

```

84

85

#### Usage Example

86

87

```python

88

import socketio

89

90

# Create and use simple client

91

sio = socketio.SimpleClient()

92

93

try:

94

# Connect to server

95

sio.connect('http://localhost:5000')

96

97

# Send a message

98

sio.emit('hello', {'name': 'Alice'})

99

100

# Wait for response

101

event, data = sio.receive(timeout=10)

102

print(f'Received {event}: {data}')

103

104

# Call with response

105

response = sio.call('get_status', timeout=5)

106

print(f'Status: {response}')

107

108

finally:

109

sio.disconnect()

110

```

111

112

### Client

113

114

A full-featured synchronous Socket.IO client with event-driven architecture, automatic reconnection, namespace support, and comprehensive configuration options.

115

116

```python { .api }

117

class Client:

118

"""

119

Full-featured synchronous Socket.IO client.

120

121

Inherits from: BaseClient

122

123

Attributes:

124

sid (str): Session ID assigned by server

125

transport (str): Current transport method

126

connected (bool): Connection status

127

"""

128

129

def __init__(self, reconnection=True, reconnection_attempts=0, reconnection_delay=1,

130

reconnection_delay_max=5, randomization_factor=0.5, logger=False,

131

serializer='default', json=None, handle_sigint=True, **kwargs):

132

"""

133

Initialize the client.

134

135

Args:

136

reconnection (bool): Enable automatic reconnection

137

reconnection_attempts (int): Maximum reconnection attempts (0 = unlimited)

138

reconnection_delay (int): Initial reconnection delay in seconds

139

reconnection_delay_max (int): Maximum reconnection delay in seconds

140

randomization_factor (float): Randomization factor for reconnection delay

141

logger (bool or Logger): Enable logging or provide custom logger

142

serializer (str): Message serializer ('default', 'pickle', 'msgpack', 'cbor')

143

json (module): Custom JSON module

144

handle_sigint (bool): Handle SIGINT signal for graceful shutdown

145

**kwargs: Additional Engine.IO client parameters

146

"""

147

148

def connect(self, url, headers=None, auth=None, transports=None, namespaces=None,

149

socketio_path='socket.io', wait=True, wait_timeout=1):

150

"""

151

Connect to a Socket.IO server.

152

153

Args:

154

url (str): Server URL

155

headers (dict, optional): HTTP headers to send

156

auth (dict, optional): Authentication credentials

157

transports (list, optional): Allowed transport methods

158

namespaces (list, optional): Namespaces to connect to

159

socketio_path (str): Socket.IO endpoint path

160

wait (bool): Wait for connection to complete

161

wait_timeout (int): Connection timeout in seconds

162

163

Raises:

164

ConnectionError: Failed to connect to server

165

"""

166

167

def wait(self):

168

"""

169

Wait until the connection ends.

170

"""

171

172

def emit(self, event, data=None, namespace=None, callback=None):

173

"""

174

Emit an event to the server.

175

176

Args:

177

event (str): Event name

178

data: Event data to send

179

namespace (str, optional): Target namespace

180

callback (callable, optional): Callback function for response

181

182

Raises:

183

DisconnectedError: Client not connected to server

184

"""

185

186

def send(self, data, namespace=None, callback=None):

187

"""

188

Send a message event to the server.

189

190

Args:

191

data: Message data to send

192

namespace (str, optional): Target namespace

193

callback (callable, optional): Callback function for response

194

195

Raises:

196

DisconnectedError: Client not connected to server

197

"""

198

199

def call(self, event, data=None, namespace=None, timeout=60):

200

"""

201

Emit an event and wait for a response.

202

203

Args:

204

event (str): Event name

205

data: Event data to send

206

namespace (str, optional): Target namespace

207

timeout (int): Response timeout in seconds

208

209

Returns:

210

Response data from server

211

212

Raises:

213

TimeoutError: No response received within timeout

214

DisconnectedError: Client not connected to server

215

"""

216

217

def disconnect(self):

218

"""

219

Disconnect from the server.

220

"""

221

222

def shutdown(self):

223

"""

224

Stop the client and all reconnection attempts.

225

"""

226

227

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

228

"""

229

Start a background task.

230

231

Args:

232

target (callable): Task function

233

*args: Task arguments

234

**kwargs: Task keyword arguments

235

236

Returns:

237

Task handle

238

"""

239

240

def sleep(self, seconds):

241

"""

242

Sleep for the given number of seconds.

243

244

Args:

245

seconds (float): Sleep duration

246

"""

247

248

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

249

"""

250

Register an event handler.

251

252

Args:

253

event (str): Event name

254

handler (callable, optional): Event handler function

255

namespace (str, optional): Target namespace

256

257

Returns:

258

Decorator function if handler not provided

259

"""

260

261

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

262

"""

263

Decorator to register an event handler.

264

265

Args:

266

event (str, optional): Event name (defaults to function name)

267

handler (callable, optional): Event handler function

268

namespace (str, optional): Target namespace

269

270

Returns:

271

Decorator function

272

"""

273

```

274

275

#### Usage Example

276

277

```python

278

import socketio

279

280

# Create client with configuration

281

sio = socketio.Client(

282

reconnection=True,

283

reconnection_attempts=5,

284

reconnection_delay=2,

285

logger=True

286

)

287

288

# Register event handlers

289

@sio.event

290

def connect():

291

print('Connected to server')

292

sio.emit('join_room', {'room': 'general'})

293

294

@sio.event

295

def disconnect():

296

print('Disconnected from server')

297

298

@sio.event

299

def message(data):

300

print(f'Received message: {data}')

301

302

@sio.on('notification')

303

def handle_notification(data):

304

print(f'Notification: {data}')

305

306

# Connect and wait

307

sio.connect('http://localhost:5000')

308

309

# Emit with callback

310

def response_handler(data):

311

print(f'Server responded: {data}')

312

313

sio.emit('chat_message', {'text': 'Hello world!'}, callback=response_handler)

314

315

# Wait for events

316

sio.wait()

317

```

318

319

### AsyncSimpleClient

320

321

Asynchronous version of SimpleClient using coroutines for non-blocking operations. Suitable for asyncio-based applications requiring simple Socket.IO communication.

322

323

```python { .api }

324

class AsyncSimpleClient:

325

"""

326

Simple asynchronous Socket.IO client with coroutine methods.

327

328

Attributes:

329

sid (str): Session ID assigned by server

330

transport (str): Current transport method

331

"""

332

333

async def connect(self, url, headers=None, auth=None, transports=None, wait_timeout=1):

334

"""

335

Connect to a Socket.IO server.

336

337

Args:

338

url (str): Server URL

339

headers (dict, optional): HTTP headers to send

340

auth (dict, optional): Authentication credentials

341

transports (list, optional): Allowed transport methods

342

wait_timeout (int): Connection timeout in seconds

343

344

Raises:

345

ConnectionError: Failed to connect to server

346

"""

347

348

async def emit(self, event, data=None):

349

"""

350

Emit an event to the server.

351

352

Args:

353

event (str): Event name

354

data: Event data to send

355

356

Raises:

357

DisconnectedError: Client not connected to server

358

"""

359

360

async def call(self, event, data=None, timeout=60):

361

"""

362

Emit an event and wait for a response.

363

364

Args:

365

event (str): Event name

366

data: Event data to send

367

timeout (int): Response timeout in seconds

368

369

Returns:

370

Response data from server

371

372

Raises:

373

TimeoutError: No response received within timeout

374

DisconnectedError: Client not connected to server

375

"""

376

377

async def receive(self, timeout=None):

378

"""

379

Wait for an event from the server.

380

381

Args:

382

timeout (int, optional): Receive timeout in seconds

383

384

Returns:

385

tuple: (event_name, event_data)

386

387

Raises:

388

TimeoutError: No event received within timeout

389

DisconnectedError: Client not connected to server

390

"""

391

392

async def disconnect(self):

393

"""

394

Disconnect from the server.

395

"""

396

```

397

398

#### Usage Example

399

400

```python

401

import asyncio

402

import socketio

403

404

async def main():

405

sio = socketio.AsyncSimpleClient()

406

407

try:

408

# Connect to server

409

await sio.connect('http://localhost:5000')

410

411

# Send message

412

await sio.emit('hello', {'name': 'Bob'})

413

414

# Wait for response

415

event, data = await sio.receive(timeout=10)

416

print(f'Received {event}: {data}')

417

418

# Call with response

419

response = await sio.call('get_info', {'query': 'status'})

420

print(f'Info: {response}')

421

422

finally:

423

await sio.disconnect()

424

425

# Run the async client

426

asyncio.run(main())

427

```

428

429

### AsyncClient

430

431

Full-featured asynchronous Socket.IO client with all the capabilities of the synchronous Client but using coroutines for non-blocking operation in asyncio applications.

432

433

```python { .api }

434

class AsyncClient:

435

"""

436

Full-featured asynchronous Socket.IO client for asyncio.

437

438

Inherits from: BaseClient

439

440

Attributes:

441

sid (str): Session ID assigned by server

442

transport (str): Current transport method

443

connected (bool): Connection status

444

"""

445

446

def __init__(self, reconnection=True, reconnection_attempts=0, reconnection_delay=1,

447

reconnection_delay_max=5, randomization_factor=0.5, logger=False,

448

serializer='default', json=None, **kwargs):

449

"""

450

Initialize the async client.

451

452

Args:

453

reconnection (bool): Enable automatic reconnection

454

reconnection_attempts (int): Maximum reconnection attempts (0 = unlimited)

455

reconnection_delay (int): Initial reconnection delay in seconds

456

reconnection_delay_max (int): Maximum reconnection delay in seconds

457

randomization_factor (float): Randomization factor for reconnection delay

458

logger (bool or Logger): Enable logging or provide custom logger

459

serializer (str): Message serializer ('default', 'pickle', 'msgpack', 'cbor')

460

json (module): Custom JSON module

461

**kwargs: Additional Engine.IO client parameters

462

"""

463

464

async def connect(self, url, headers=None, auth=None, transports=None, namespaces=None,

465

socketio_path='socket.io', wait=True, wait_timeout=1):

466

"""

467

Connect to a Socket.IO server.

468

469

Args:

470

url (str): Server URL

471

headers (dict, optional): HTTP headers to send

472

auth (dict, optional): Authentication credentials

473

transports (list, optional): Allowed transport methods

474

namespaces (list, optional): Namespaces to connect to

475

socketio_path (str): Socket.IO endpoint path

476

wait (bool): Wait for connection to complete

477

wait_timeout (int): Connection timeout in seconds

478

479

Raises:

480

ConnectionError: Failed to connect to server

481

"""

482

483

async def wait(self):

484

"""

485

Wait until the connection ends.

486

"""

487

488

async def emit(self, event, data=None, namespace=None, callback=None):

489

"""

490

Emit an event to the server.

491

492

Args:

493

event (str): Event name

494

data: Event data to send

495

namespace (str, optional): Target namespace

496

callback (callable, optional): Async callback function for response

497

498

Raises:

499

DisconnectedError: Client not connected to server

500

"""

501

502

async def send(self, data, namespace=None, callback=None):

503

"""

504

Send a message event to the server.

505

506

Args:

507

data: Message data to send

508

namespace (str, optional): Target namespace

509

callback (callable, optional): Async callback function for response

510

511

Raises:

512

DisconnectedError: Client not connected to server

513

"""

514

515

async def call(self, event, data=None, namespace=None, timeout=60):

516

"""

517

Emit an event and wait for a response.

518

519

Args:

520

event (str): Event name

521

data: Event data to send

522

namespace (str, optional): Target namespace

523

timeout (int): Response timeout in seconds

524

525

Returns:

526

Response data from server

527

528

Raises:

529

TimeoutError: No response received within timeout

530

DisconnectedError: Client not connected to server

531

"""

532

533

async def disconnect(self):

534

"""

535

Disconnect from the server.

536

"""

537

538

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

539

"""

540

Start a background task.

541

542

Args:

543

target (coroutine): Async task function

544

*args: Task arguments

545

**kwargs: Task keyword arguments

546

547

Returns:

548

asyncio.Task: Task handle

549

"""

550

551

async def sleep(self, seconds):

552

"""

553

Sleep for the given number of seconds.

554

555

Args:

556

seconds (float): Sleep duration

557

"""

558

559

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

560

"""

561

Register an async event handler.

562

563

Args:

564

event (str): Event name

565

handler (coroutine, optional): Async event handler function

566

namespace (str, optional): Target namespace

567

568

Returns:

569

Decorator function if handler not provided

570

"""

571

572

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

573

"""

574

Decorator to register an async event handler.

575

576

Args:

577

event (str, optional): Event name (defaults to function name)

578

handler (coroutine, optional): Async event handler function

579

namespace (str, optional): Target namespace

580

581

Returns:

582

Decorator function

583

"""

584

```

585

586

#### Usage Example

587

588

```python

589

import asyncio

590

import socketio

591

592

# Create async client

593

sio = socketio.AsyncClient(

594

reconnection=True,

595

reconnection_attempts=3,

596

logger=True

597

)

598

599

# Register async event handlers

600

@sio.event

601

async def connect():

602

print('Connected to server')

603

await sio.emit('join_room', {'room': 'async-users'})

604

605

@sio.event

606

async def disconnect():

607

print('Disconnected from server')

608

609

@sio.event

610

async def message(data):

611

print(f'Received message: {data}')

612

# Process message asynchronously

613

await process_message(data)

614

615

@sio.on('notification')

616

async def handle_notification(data):

617

print(f'Notification: {data}')

618

619

async def process_message(data):

620

# Simulate async processing

621

await asyncio.sleep(0.1)

622

print(f'Processed: {data}')

623

624

async def main():

625

# Connect to server

626

await sio.connect('http://localhost:5000')

627

628

# Emit with async callback

629

async def response_handler(data):

630

print(f'Server responded: {data}')

631

632

await sio.emit('chat_message', {'text': 'Hello async world!'}, callback=response_handler)

633

634

# Wait for events

635

await sio.wait()

636

637

# Run the async client

638

asyncio.run(main())

639

```

640

641

## Context Manager Support

642

643

Both SimpleClient and AsyncSimpleClient support context manager syntax for automatic connection management:

644

645

```python

646

# Synchronous context manager

647

with socketio.SimpleClient() as sio:

648

sio.connect('http://localhost:5000')

649

sio.emit('hello', {'name': 'World'})

650

event, data = sio.receive()

651

652

# Asynchronous context manager

653

async with socketio.AsyncSimpleClient() as sio:

654

await sio.connect('http://localhost:5000')

655

await sio.emit('hello', {'name': 'World'})

656

event, data = await sio.receive()

657

```