什么是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协议

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.


Please enable JavaScript to view the comments powered by Disqus.

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

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

  1. 如何在python中找到两个日期时间对象之间的时差?

    本文翻译自:How do I find the time difference between two datetime objects in python? 如何分辨两个datetime对象之间的时 ...

  2. 如何在Python中声明一个数组?

    如何在Python中声明数组? 我在文档中找不到任何对数组的引用. #1楼 这个怎么样... >>> a = range(12) >>> a [0, 1, 2, 3 ...

  3. 如何在Python中捕获SIGINT?

    我正在研究启动多个进程和数据库连接的python脚本. 我不时地想用Ctrl + C信号杀死脚本,我想进行一些清理. 在Perl中,我可以这样做: $SIG{'INT'} = 'exit_gracef ...

  4. 如何在Python中解析YAML文件

    如何在Python中解析YAML文件? #1楼 不依赖C标头的最简单,最纯净的方法是PyYaml( 文档 ): #!/usr/bin/env pythonimport yamlwith open(&q ...

  5. 如何在Python中反转列表?

    如何在Python中执行以下操作? array = [0, 10, 20, 40] for (i = array.length() - 1; i >= 0; i--) 我需要一个数组的元素,但是 ...

  6. python set 排序_python set 排序_如何在Python中使用sorted()和sort()

    点击"蓝字"关注我们 ?"Python基础知识" 大卫·丰达科夫斯基  著 18财税3班 李潇潇    译 日期:2019年5月6日 一. 使用sorted() ...

  7. python 参数个数 同名函数_如何在python中编写不同参数的同名方法

    我在Java背景下学习Python(3.x). 我有一个python程序,我在其中创建一个personObject并将其添加到列表中.p = Person("John") list ...

  8. python if语句多个条件-关于函数:如何在python中为一个if语句提供多个条件

    本问题已经有最佳答案,请猛点这里访问. 所以我在用python 3.1.5编写一些代码,这些代码需要有多个条件才能发生某些事情.例子: 1 2 3 4 5def example(arg1, arg2, ...

  9. python中range 10 0_如何在python中使用range方法

    如何在python中使用range方法 发布时间:2021-01-05 16:55:23 来源:亿速云 阅读:94 作者:Leah 如何在python中使用range方法?很多新手对此不是很清楚,为了 ...

  10. python中变量名有哪些_Python变量范围有哪些?如何在Python中定义变量?

    Python变量范围有哪些?如何在Python中定义变量?在Python编程语言中,变量的范围是该变量可见或可访问的那段代码.更准确地说,不是每个程序的每个部分都可以访问所有变量.而且,有时范围也是持 ...

最新文章

  1. Twilio能够在市场低谷成功上市,为什么以及有什么意义?
  2. iOS--SDAutolayout宽度自适应
  3. 软件项目质量保证——编码规范
  4. Linux下的Backlight子系统
  5. 2019年第十届蓝桥杯 - 省赛 - C/C++大学B组 - A. 组队
  6. 4.3串的模式匹配算法(BF算法)
  7. 资源:代码舞动动画 提供gif图片(含程序、源码、下载地址)
  8. java实体类的功能_(转载) java实体类的作用
  9. Junit单元测试/反射/注解
  10. 城域容灾体系的突破性进展
  11. 计算坐标系中两个点之间的距离c语言,如何求坐标系中两点间的距离
  12. 动态规划法(入门)——最大正方形、最大长方形
  13. 32把数组排成最小的数({3,32,321}输出最小数字为321323)
  14. (4)ArcGIS 10.2 去除要素的Z值和M值
  15. 《生命》第三集:Mammals (哺乳动物)
  16. ADB自动化线刷升级安卓车机版本
  17. Android TextView字体样式设置
  18. JDO持久 (jdbc ejb)
  19. [Android开发] Xposed 插件开发之一: Xposed入门
  20. R包SangerSeqR处理ab1数据

热门文章

  1. php cdata,PHPcdata处理(详细介绍)_PHP教程
  2. axios安装_Vue脚手架安装,与基本语法(干货)
  3. cad应用程序的组件中发生了未经处理的异常_什么是CAD/CAM?
  4. Pytorch:数据并行和模型并行,解决训练过程中内存分配不均衡的问题
  5. Latex 表格 行合并,列合并,控制行间距 单元格宽度
  6. 【动态规划】0/1背包问题
  7. 机器学习:样本集、验证集(开发集)、测试集
  8. 关于apache的虚拟主机配置
  9. 迭代获取ViewState
  10. 关于阿拉伯数字转化成为大写汉字