This package contains two Socket.IO clients:
- The
socketio.Client()
class creates a client compatible with thestandard Python library. - The
socketio.AsyncClient()
class creates a client compatible withtheasyncio
package.
The methods in the two clients are the same, with the only difference that inthe asyncio
client most methods are implemented as coroutines.
- Jun 21, 2018 Files for sockets, version 1.0.0; Filename, size File type Python version Upload date Hashes; Filename, size sockets-1.0.0-py3-none-any.whl (4.5 kB) File type Wheel Python version py3 Upload date Jun 21, 2018 Hashes View.
- Socket API Overview. Python’s socket module provides an interface to the Berkeley sockets API.This is the module that we’ll use and discuss in this tutorial. The primary socket API functions and methods in this module are.
Welcome to a tutorial on sockets with Python 3. We have a lot to cover, so let's just jump right in. The socket library is a part of the standard library, so you already have it. Import socket # create the socket # AFINET ipv4 # SOCKSTREAM TCP s = socket.socket(socket.AFINET, socket.SOCKSTREAM). An open-source universal messaging library. Pip install pyzmq. Server: # # Hello World server in Python # Binds REP socket to tcp://.:5555 # Expects b'Hello' from client, replies with b'World' # import time import zmq context = zmq.
Installation¶
To install the standard Python client along with its dependencies, use thefollowing command:
If instead you plan on using the asyncio
client, then use this:
Creating a Client Instance¶
To instantiate an Socket.IO client, simply create an instance of theappropriate client class:
Defining Event Handlers¶
The Socket.IO protocol is event based. When a server wants to communicate witha client it emits an event. Each event has a name, and a list ofarguments. The client registers event handler functions with thesocketio.Client.event()
or socketio.Client.on()
decorators:
In the first example the event name is obtained from the name of thehandler function. The second example is slightly more verbose, but itallows the event name to be different than the function name or to includecharacters that are illegal in function names, such as spaces.
For the asyncio
client, event handlers can be regular functions as above,or can also be coroutines:
The connect
, connect_error
and disconnect
events are special; theyare invoked automatically when a client connects or disconnects from theserver:
The connect_error
handler is invoked when a connection attempt fails. Ifthe server provides arguments, these are passed on to the handler. The servercan use an argument to provide information to the client regarding theconnection failure.
The disconnect
handler is invoked for application initiated disconnects,server initiated disconnects, or accidental disconnects, for example due tonetworking failures. In the case of an accidental disconnection, the client isgoing to attempt to reconnect immediately after invoking the disconnecthandler. As soon as the connection is re-established the connect handler willbe invoked once again.
If the server includes arguments with an event, those are passed to thehandler function as arguments.
Connecting to a Server¶
The connection to a server is established by calling the connect()
method:
In the case of the asyncio
client, the method is a coroutine:
Upon connection, the server assigns the client a unique session identifier.The applicaction can find this identifier in the sid
attribute:
Emitting Events¶
The client can emit an event to the server using the emit()
method:
Or in the case of asyncio
, as a coroutine:
The single argument provided to the method is the data that is passed onto the server. The data can be of type str
, bytes
, dict
,list
or tuple
. When sending a tuple
, the elements in it need tobe of any of the other four allowed types. The elements of the tuple will bepassed as multiple arguments to the server-side event handler function.
The emit()
method can be invoked inside an event handler as a responseto a server event, or in any other part of the application, including inbackground tasks.
Event Callbacks¶
When a server emits an event to a client, it can optionally provide acallback function, to be invoked as a way of acknowledgment that the serverhas processed the event. While this is entirely managed by the server, theclient can provide a list of return values that are to be passed on to thecallback function set up by the server. This is achieved simply by returningthe desired values from the handler function:
Likewise, the client can request a callback function to be invoked after theserver has processed an event. The socketio.Server.emit()
method has anoptional callback
argument that can be set to a callable. If thisargument is given, the callable will be invoked after the server has processedthe event, and any values returned by the server handler will be passed asarguments to this function.
Install Socket In Python
Namespaces¶
The Socket.IO protocol supports multiple logical connections, all multiplexedon the same physical connection. Clients can open multiple connections byspecifying a different namespace on each. Namespaces use a path syntaxstarting with a forward slash. A list of namespaces can be given by the clientin the connect()
call. For example, this example creates two logicalconnections, the default one plus a second connection under the /chat
namespace:
To define event handlers on a namespace, the namespace
argument must beadded to the corresponding decorator:
Install Socket For Python In C++
Likewise, the client can emit an event to the server on a namespace byproviding its in the emit()
call:
If the namespaces
argument of the connect()
call isn’t given, anynamespaces used in event handlers are automatically connected.
Class-Based Namespaces¶
As an alternative to the decorator-based event handlers, the event handlersthat belong to a namespace can be created as methods of a subclass ofsocketio.ClientNamespace
:
For asyncio based servers, namespaces must inherit fromsocketio.AsyncClientNamespace
, and can define event handlers ascoroutines if desired:
When class-based namespaces are used, any events received by the client aredispatched to a method named as the event name with the on_
prefix. Forexample, event my_event
will be handled by a method named on_my_event
.If an event is received for which there is no corresponding method defined inthe namespace class, then the event is ignored. All event names used inclass-based namespaces must use characters that are legal in method names.
As a convenience to methods defined in a class-based namespace, the namespaceinstance includes versions of several of the methods in thesocketio.Client
and socketio.AsyncClient
classes thatdefault to the proper namespace when the namespace
argument is not given.
In the case that an event has a handler in a class-based namespace, and also adecorator-based function handler, only the standalone function handler isinvoked.
Disconnecting from the Server¶
Install Socket For Python In Linux
At any time the client can request to be disconnected from the server byinvoking the disconnect()
method:
For the asyncio
client this is a coroutine:
Managing Background Tasks¶
When a client connection to the server is established, a few backgroundtasks will be spawned to keep the connection alive and handle incomingevents. The application running on the main thread is free to do anywork, as this is not going to prevent the functioning of the Socket.IOclient.
If the application does not have anything to do in the main thread andjust wants to wait until the connection with the server ends, it can callthe wait()
method:
Or in the asyncio
version:
For the convenience of the application, a helper function is provided tostart a custom background task:
The arguments passed to this method are the background function and anypositional or keyword arguments to invoke the function with.
Here is the asyncio
version:
Note that this function is not a coroutine, since it does not wait for thebackground function to end. The background function must be a coroutine.
The sleep()
method is a second convenience function that is provided forthe benefit of applications working with background tasks of their own:
Or for asyncio
:
The single argument passed to the method is the number of seconds to sleepfor.
Debugging and Troubleshooting¶
To help you debug issues, the client can be configured to output logs to theterminal:
The logger
argument controls logging related to the Socket.IO protocol,while engineio_logger
controls logs that originate in the low-levelEngine.IO transport. These arguments can be set to True
to output logs tostderr
, or to an object compatible with Python’s logging
packagewhere the logs should be emitted to. A value of False
disables logging.
Logging can help identify the cause of connection problems, unexpecteddisconnections and other issues.