热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

什么是WebSocket,以及如何在Python中使用它?

什么是WebSocket?(WhatisWebSocket?)WebSocketisacommunicationsprotocolwhichprovidesafull

什么是WebSocket? (What is WebSocket?)

WebSocket is a communications protocol which provides a full-duplex communication channel over a single TCP connection. WebSocket protocol is standardized by the IETF as RFC 6455.

WebSocket是一种通信协议,可通过单个TCP连接提供全双工通信通道。 WebSocket协议由IETF标准化为RFC 6455。

WebSocket and HTTP, both distinct and are located in layer 7 of the OSI model and depend on TCP at layer 4. RFC 6455 states that "WebSocket is designed to work over HTTP ports 80 and 443 as well as to support HTTP proxies and intermediaries", making it compatible with HTTP protocol. WebSocket handshake uses the HTTP Upgrade header to change from the HTTP to WebSocket protocol.

WebSocket和HTTP截然不同,位于OSI模型的第7层中,并在第4层上依赖于TCP。RFC 6455指出“ WebSocket设计为可通过HTTP端口80和443工作,并支持HTTP代理和中介” ,使其与HTTP协议兼容。 WebSocket握手使用HTTP升级标头将HTTP更改为WebSocket协议。

WebSocket protocol enables interaction between a web browser or any client application and a web server, facilitating the real-time data transfer from and to the server.

WebSocket协议支持Web浏览器或任何客户端应用程序与Web服务器之间的交互,从而促进了服务器之间的实时数据传输。

Most of the newer version of browsers such as Google Chrome, IE, Firefox, Safari, and Opera support the WebSocket protocol.

大多数新版本的浏览器(例如Google Chrome,IE,Firefox,Safari和Opera)都支持WebSocket协议

WebSocket in Python

Python WebSocket实现 (Python WebSocket implementations)

There are multiple projects which provide either the implementations of web socket or provide with examples for the same.

有多个项目可以提供Web套接字的实现,也可以提供示例。

  1. Autobahn – uses Twisted and Asyncio to create the server-side components, while AutobahnJS provides client-side.

    Autobahn –使用Twisted和Asyncio创建服务器端组件,而AutobahnJS提供客户端。

  2. Flask – SocketIO is a flask extension.

    Flask – SocketIO是Flask的扩展。

  3. WebSocket –client provides low-level APIs for web sockets and works on both Python2 and Python3.

    WebSocket –client提供了用于Web套接字的低级API,并且可以在Python2和Python3上使用。

  4. Django Channels is built on top of WebSockets and useful in and easy to integrate the Django applications.

    Django Channels构建于WebSockets之上,在Django应用程序中非常有用且易于集成。

使用WebSocket客户端库的Python应用程序示例 (Python Example of application using WebSocket-client library)

The WebSocket client library is used to connect to a WebSocket server,

WebSocket客户端库用于连接到WebSocket服务器,

Prerequisites:

先决条件:

Install WebSocket client using pip within the virtual environment,

在虚拟环境中使用pip安装WebSocket客户端,

  • Create a virtual environment

    创建一个虚拟环境

    python3 -m venv /path/to/virtual/environment

    python3 -m venv / path / to / virtual / environment

    >> python3 -m venv venv

    >> python3 -m venv venv

  • Source the virtual environment

    采购虚拟环境

    >> source venv/bin/activate

    >>源venv / bin / activate

  • Install the websocket-client using pip

    使用pip安装websocket-client

    >> (venv) pip3 install websocket_client

    >>(venv)pip3安装websocket_client

Collecting websocket_client==0.56.0 (from -r requirements.txt (line 1))
Downloading https://files.pythonhosted.org/packages/29/19/44753eab1fdb50770ac69605527e8859468f3c0fd7dc5a76dd9c4dbd7906/websocket_client-0.56.0-py2.py3-none-any.whl (200kB)
100% | | 204kB 2.7MB/s
Collecting six (from websocket_client==0.56.0->-r requirements.txt (line 1))
Downloading https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl
Installing collected packages: six, websocket-client
Successfully installed six-1.12.0 websocket-client-0.56.0

The below example is compatible with python3, and tries to connect to a web socket server.

以下示例与python3兼容,并尝试连接到Web套接字服务器。

Example 1: Short lived connection

示例1:短暂的连接

from websocket import create_connection
def short_lived_connection():
ws = create_connection("ws://localhost:4040/")
print("Sending 'Hello Server'...")
ws.send("Hello, Server")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()
if __name__ == '__main__':
short_lived_connection()

Output

输出量

Sending 'Hello, World'...
Sent
Receiving...
Received 'hello world'

The short lived connection, is useful when the client doesn't have to keep the session alive for ever and is used to send the data only at a given instant.

短暂的连接非常有用,当客户端不必使会话永远保持活动状态,并且仅用于在给定瞬间发送数据时。

Example 2: Long Lived connection

示例2:长期连接

import websocket
def on_message(ws, message):
'''
This method is invoked when ever the client
receives any message from server
'''
print("received message as {}".format(message))
ws.send("hello again")
print("sending 'hello again'")
def on_error(ws, error):
'''
This method is invoked when there is an error in connectivity
'''
print("received error as {}".format(error))
def on_close(ws):
'''
This method is invoked when the connection between the
client and server is closed
'''
print("Connection closed")
def on_open(ws):
'''
This method is invoked as soon as the connection between
client and server is opened and only for the first time
'''
ws.send("hello there")
print("sent message on open")
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:4040/",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()

Output

输出量

--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:4040
Origin: http://localhost:4040
Sec-WebSocket-Key: q0+vBfXgMvGGywjDaHZWiw==
Sec-WebSocket-Version: 13
-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: /YqMq5iNGOMjtELPGCZsnozMSlw=
Date: Sun, 15 Sep 2019 23:34:04 GMT
Server: Python/3.7 websockets/8.0.2
-----------------------
send: b'\x81\x8b\xcb\xeaY.\xa3\x8f5B\xa4\xca-F\xae\x98


TOP Interview Coding Problems/Challenges

  • Run-length encoding (find/print frequency of letters in a string)

  • Sort an array of 0's, 1's and 2's in linear time complexity

  • Checking Anagrams (check whether two string is anagrams or not)

  • Relative sorting algorithm

  • Finding subarray with given sum

  • Find the level in a binary tree with given sum K

  • Check whether a Binary Tree is BST (Binary Search Tree) or not

  • 1[0]1 Pattern Count

  • Capitalize first and last letter of each word in a line

  • Print vertical sum of a binary tree

  • Print Boundary Sum of a Binary Tree

  • Reverse a single linked list

  • Greedy Strategy to solve major algorithm problems

  • Job sequencing problem

  • Root to leaf Path Sum

  • Exit Point in a Matrix

  • Find length of loop in a linked list

  • Toppers of Class

  • Print All Nodes that don't have Sibling

  • Transform to Sum Tree

  • Shortest Source to Destination Path




Comments and Discussions


Ad:
Are you a blogger? Join our Blogging forum.


翻译自: https://www.includehelp.com/python/what-is-websocket-and-how-to-use-it-in-python.aspx



推荐阅读
author-avatar
安全小护士
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有