Technology Sharing

Socket.IO in Python

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Socket.IOIt is a real-time, bidirectional, and event-based communication library based on WebSocket. It was originally designed for Node.js, but now has implementations in multiple languages, including Python. In Python,python-socketioIt is a popular library that allows you to easily implement Socket.IO clients and servers. This library is particularly useful for building web applications that require real-time data exchange, such as chat applications, real-time notification systems, games, etc.

Features of Python-SocketIO

  • Two-way communication: Clients and servers can send and receive messages to each other.
  • Automatic reconnection: The client can automatically try to reconnect to the server, which is particularly useful when the network is unstable.
  • Event-driven: The event-based programming model makes development more intuitive and flexible.
  • Multi-language support: Although we are discussing Python here, the Socket.IO ecosystem supports multiple languages ​​and platforms for easy integration.
  • Compatible with WebSocket and long polling: Even in older browsers that do not support WebSocket, real-time communication can be achieved through technologies such as long polling.

Install

You can install it via pippython-socketio

pip install python-socketio

If you also want to create a web server and want it to act as a Socket.IO server at the same time, you may also need to installFlask-SocketIO(A Flask extension that integrates Flask and Socket.IO):

pip install Flask-SocketIO

Creating a server using Python-SocketIO

The following is a simpleFlask-SocketIOServer example, which uses the Flask framework and integrates Socket.IO:

  1. from flask import Flask, render_template
  2. from flask_socketio import SocketIO, send
  3. app = Flask(__name__)
  4. app.config['SECRET_KEY'] = 'secret!'
  5. socketio = SocketIO(app)
  6. @app.route('/')
  7. def index():
  8. return render_template('index.html')
  9. @socketio.on('message')
  10. def handleMessage(msg):
  11. print('Message: ' + msg)
  12. send(msg, broadcast=True)
  13. if __name__ == '__main__':
  14. socketio.run(app)

In this example, the server listens/Routing, and rendering an HTML page (you need to create this page yourself and import the Socket.IO client library). The server also listens for amessageWhen this event is received, it prints the message content and broadcasts the message back to all connected clients.

Client

On the client side (usually JavaScript in a browser), you need to import the Socket.IO client library and establish a connection with the server. Here is a simple client example:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Socket.IO chat</title>
  5. <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
  6. <script>
  7. var socket = io('http://localhost:5000');
  8. socket.on('connect', function() {
  9. console.log('Connected to the server!');
  10. });
  11. socket.on('message', function(msg) {
  12. console.log('Received message: ' + msg);
  13. });
  14. function sendMessage() {
  15. var input = document.getElementById('messageInput');
  16. socket.emit('message', input.value);
  17. input.value = '';
  18. }
  19. </script>
  20. </head>
  21. <body>
  22. <input type="text" id="messageInput" autocomplete="off" /><button onclick="sendMessage()">Send</button>
  23. </body>
  24. </html>

In this example, the client connects to the server, listeningmessageevent, and defines asendMessageFunction to send a message to the server.

Summarize

python-socketioandFlask-SocketIOProvides powerful tools for building real-time web applications. By leveraging WebSocket and event-driven programming models, you can easily implement complex real-time interactive functions.

We will continue to update and share relevant content in the future.Remember to pay attention!