在python中使用websockets

WebSocket (WebSocket)

Websocket is a communications protocol, providing full-duplex bi-directional communication over a single TCP connection.

Websocket是一种通信协议,可通过单个TCP连接提供全双工双向通信。

To understand Websockets, first, we have to have a clear understanding of HTTP protocol cause both go hand in hand.

要了解Websocket,首先,我们必须对HTTP协议有一个清晰的了解,因为两者相互关联。

Image for post
HTTP protocol life cycle
HTTP协议生命周期

HTTP is a protocol which allows the fetching of resources, such as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser.

HTTP是一种协议 ,它允许资源,诸如HTML文档的抓取。 它是Web上任何数据交换的基础,并且是客户端-服务器协议,这意味着请求是由收件人(通常是Web浏览器)发起的。

HyperText Transfer Protocol is an application layer is a stateless application-level protocol where generally client requests information with headers using actions like GET, POST, PUT … and server sends the response back to the client and the connection is closed.

超文本传输​​协议是应用程序层,是一种无状态的应用程序级别协议,通常,客户端使用诸如GET,POST,PUT…之类的动作请求带有标头的信息,然后服务器将响应发送回客户端,并关闭连接。

For every communication, HTTP protocol will open a connection, data exchange then the connection is closed.

对于每次通信,HTTP协议都会打开一个连接,进行数据交换然后关闭该连接。

If the requirement is to fetch the data continuously from the server. For example fetch the realtime data for cryptocurrency exchange, gaming application or for a chat application. Then there will be multiple HTTP calls to the server.

如果要求是从服务器连续获取数据。 例如,获取实时数据以用于加密货币交换,游戏应用程序或聊天应用程序。 然后将有多个HTTP调用到服务器。

SAVE the SERVER

保存服务器

Image for post
Photo by Vilmar Simion on Unsplash
Vilmar SimionUnsplash拍摄的照片

How’s the Websocket is different from traditional HTTP protocols. Websockets uses bi-directional communication and the connection will not break until the client or server decides to terminate the connection.

Websocket与传统的HTTP协议有何不同。 Websockets使用双向通信,并且在客户端或服务器决定终止连接之前,连接不会中断。

Image for post
https://blog.stanko.io/do-you-really-need-websockets-343aed40aa9b https://blog.stanko.io/do-you-really-need-websockets-343aed40aa9b

Websockets的生命周期 (The life cycle of Websockets)

握手 (Handshake)

Websocket is also an application layer protocol and it is an HTTP upgrade that uses the same TCP connection over ws://

Websocket也是应用程序层协议,它是HTTP升级,它通过ws://使用相同的TCP连接

In simple terms client asks for the server that, can we make a WebSocket connection and in reply server will say, yeah buddy let’s upgrade the connection to WS

简而言之,客户端请求服务器,我们能否建立WebSocket连接,服务器会回复说,是的,哥们,让我们将连接升级到WS

This is called the handshake and the connection is established between client and server.

这称为握手,并且在客户端和服务器之间建立了连接。

开放持久的连接 (Open and Persistent Connection)

Once the connection is established communication happens in terms of bi-directional message communication.

一旦建立连接,就进行双向消息通信。

连接已关闭 (Connection Closed)

Once the connection is established its stays forever until the client or server wants to terminate the connection.

建立连接后,它将一直保留到客户端或服务器要终止连接为止。

Image for post

Enough of the theory, let’s dive into the implementation. So to have a WebSocket connection we first need to have a client and a server. For the implementation, we are using Python’s Flask Server that is a microframework.

理论足够多,让我们深入研究实现。 因此,要建立WebSocket连接,我们首先需要拥有一个客户端和一个服务器。 对于实现,我们使用的是微框架的Python Flask Server。

Image for post
tenor
男高音

We will be using Socket.io for the client socket library and Flask-SocketiIO for the server WebSocket library for our example.

对于我们的示例 ,我们将使用Socket.io作为客户端套接字库,并使用Flask-SocketiIO作为服务器WebSocket库。

Flask-SocketIO (Flask-SocketIO)

Lets first install all our dependencies to run the project like flask-socketio or may be flask if that is not installed yet. As the WebSocket can connect to n number of clients so flask has to use some asynchronous libraries like Eventlet or Gevent. So in our case, we are installing Eventlet.

首先让我们安装所有依赖项来运行项目,例如flask-socketio;如果尚未安装,则可以是flask。 由于WebSocket可以连接到n个客户端,因此flask必须使用一些异步库,例如Eventlet或Gevent。 因此,在本例中,我们正在安装Eventlet。

To run the project with Eventlet thread library let’s install Gunicorn web server or maybe you can use UWsgi server.

要使用Eventlet线程库运行项目,请安装Gunicorn Web服务器,或者也许可以使用UWsgi服务器。

pip install flask
pip install flask-socketio
pip install eventlet
pip install gunicorn

Now we just have to set up the flask project and initialize the flask-socketio and for more information please visit the official docs of flask-socketio

现在我们只需要设置flask项目并初始化flask-socketio,有关更多信息,请访问flask-socketio的官方文档

from flask import Flask, render_template
from flask_socketio import SocketIO


# Initializing the flask object
app = Flask(__name__)


#  Initializing the flask-websocketio
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)


# If you are running it using python <filename> then below command will be used
if __name__ == '__main__':
    socketio.run(app)

Now by default, the server is running on 5000 port with WebSocket. Now we just need to connect from the client to the server. Let’s make the connection using Socket.io

现在默认情况下,服务器通过WebSocket在5000端口上运行。 现在,我们只需要从客户端连接到服务器即可。 让我们使用Socket.io建立连接

套接字 (Socket.io)

To install socket.io either you can use CDN for it or if you are using npm then just fire

要安装socket.io,可以使用CDN,或者如果使用npm,则只需启动

npm install socket.io-client

And to simplify our solution we are using CDN link

为了简化我们的解决方案,我们使用CDN链接

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
    const socket = io('http://localhost:5000')


    socket.on('connect', () => {
      console.log("socket connected");
    });


</script>

So above code will connect to localhost server on port 5000 on which we have already started our flask server with WebSocket. Now our client is connected with our server and you can check that in the web console with the statement as socket connected

因此,上面的代码将连接到端口5000上的localhost服务器,我们已经在该端口上使用WebSocket启动了flask服务器。 现在,我们的客户端已与我们的服务器连接,您可以在Web控制台中检查以下内容,并声明为socket socket

Image for post

And to check whether the client is connected to the server or not just add the below code.

并检查客户端是否已连接到服务器,只需添加以下代码。

@socket_io.on('connect')def test_connect():
print("socket connected")

Now as the client and server are connected then there’s an HTTP upgrade happened and the connection is made on ws://localhost:5000 with status code as 101(Switching Protocols). And now all the data exchange will happen on the same network call only. You can test that our in the network tab there is a header called WS in chrome.

现在,当客户端和服务器已连接时,便进行了HTTP升级,并在ws:// localhost:5000上建立了连接,状态代码为101(交换协议)。 现在,所有数据交换将仅在同一网络呼叫上进行。 您可以测试我们的网络标签中是否有一个名为WS的标头。

Image for post

So let’s send some data from client to the server over the same network without creating any new network call. To send a message from client to server you can either use send or emit method.

因此,让我们通过同一网络将客户端中的一些数据发送到服务器,而无需创建任何新的网络调用。 要将消息从客户端发送到服务器,可以使用send或emit方法。

socket.emit('message', { 'hello': 'world' });

You can even send the data to the server with a custom event just change the first parameter to anything else. But just be sure that there should be a receiver configured on the server that is listening to that event.

您甚至可以通过自定义事件将数据发送到服务器,只需将第一个参数更改为其他任何参数即可。 但是只需确保在服务器上配置了正在侦听该事件的接收器。

With Flask-SocketIO the server needs to register handlers for these events, similarly to how routes are handled by view functions.

使用Flask-SocketIO,服务器需要为这些事件注册处理程序,这与视图函数如何处理路由类似。

The following example creates a server-side event handler for an unnamed event:

下面的示例为一个未命名事件创建服务器端事件处理程序:

@socketio.on('message')def handle_message(message):
print('received message: ' + message)

The above example uses string messages. Another type of unnamed events use JSON data:

上面的示例使用字符串消息。 另一种类型的未命名事件使用JSON数据:

@socketio.on('json')def handle_json(json):
print('received json: ' + str(json))

SocketIO event handlers defined as shown in the previous section can send reply messages to the connected client using the send() and emit() functions.

如上一节中所示定义的SocketIO事件处理程序可以使用send()emit()函数将答复消息发送到连接的客户端。

The following examples bounce received events back to the client that sent them:

以下示例将收到的事件退回给发送事件的客户端:

from flask_socketio import send, emit@socketio.on('message')def handle_message(message):
send(message)@socketio.on('json')def handle_json(json):
send(json, json=True)@socketio.on('my event')def handle_my_custom_event(json):
emit('my response', json)

Note how send() and emit() are used for unnamed and named events respectively.

注意send()emit()分别用于未命名事件和已命名事件。

广播 (Broadcasting)

Another very useful feature of SocketIO is the broadcasting of messages. Flask-SocketIO supports this feature with the broadcast=True optional argument to send() and emit():

SocketIO的另一个非常有用的功能是消息的广播。 烧瓶-SocketIO支持与该功能broadcast=True可选参数send()emit()

@socketio.on('my event')def handle_my_custom_event(data):
emit('my response', data, broadcast=True)

When a message is sent with the broadcast option enabled, all clients connected to the namespace receive it, including the sender.

在启用广播选项的情况下发送消息时,所有连接到名称空间的客户端(包括发送者)都将收到该消息。

And to handle the messages coming from the server, we have to register a new handler for the given event on the client-side, so that client can get the message from the server.

为了处理来自服务器的消息,我们必须在客户端为给定事件注册一个新的处理程序,以便客户端可以从服务器获取消息。

socket.on('my event', (data) => {
console.log(data); // this will log the output that server has send to the client
});

在哪里使用Websockets代替传统的HTTP调用 (Where to use Websockets instead of traditional HTTP calls)

  1. Realtime applications like bitcoin exchange. Just check out the link and open the chrome dev-tools network tab you can see massive to and fro of the data happening.

    实时应用,如比特币交换 。 只需查看链接并打开chrome dev-tools网络标签,您就可以看到大量的数据往返。

Image for post

2. Chat application. You can check out Socket.io chat application that uses the WebSocket concept. Please check out the link for chat application demo.

2.聊天应用程序。 您可以签出使用WebSocket概念的Socket.io聊天应用程序。 请查看有关聊天应用程序演示的链接

结论 (Conclusion)

Websockets are very easy, lightweight and super interesting when you see a lot of data is flowing to and fro in a single call, without bombarding the server with too much of network calls.

当您在单个呼叫中看到大量数据往返时,Websocket非常简单,轻巧且非常有趣,而无需通过过多的网络呼叫来轰炸服务器。

This was just my understanding of Websocket. I hope, it has helped you. If you want to discuss with me about anything or anything related to tech, you can contact me here or on Linkedin.

这只是我对Websocket的理解。 希望对您有帮助。 如果您想与我讨论有关技术的任何事宜,可以在此处或通过Linkedin与我联系。

翻译自: https://medium.com/koko-networks/using-websockets-with-python-4396e54d36e6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值