热门标签 | 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



推荐阅读
  • 为什么多数程序员难以成为架构师?
    探讨80%的程序员为何难以晋升为架构师,涉及技术深度、经验积累和综合能力等方面。本文将详细解析Tomcat的配置和服务组件,帮助读者理解其内部机制。 ... [详细]
  • Nacos 0.3 数据持久化详解与实践
    本文详细介绍了如何将 Nacos 0.3 的数据持久化到 MySQL 数据库,并提供了具体的步骤和注意事项。 ... [详细]
  • 包含phppdoerrorcode的词条 ... [详细]
  • 基于iSCSI的SQL Server 2012群集测试(一)SQL群集安装
    一、测试需求介绍与准备公司计划服务器迁移过程计划同时上线SQLServer2012,引入SQLServer2012群集提高高可用性,需要对SQLServ ... [详细]
  • IOS Run loop详解
    为什么80%的码农都做不了架构师?转自http:blog.csdn.netztp800201articledetails9240913感谢作者分享Objecti ... [详细]
  • javascript分页类支持页码格式
    前端时间因为项目需要,要对一个产品下所有的附属图片进行分页显示,没考虑ajax一张张请求,所以干脆一次性全部把图片out,然 ... [详细]
  • 本文介绍了如何查看PHP网站及其源码的方法,包括环境搭建、本地测试、源码查看和在线查找等步骤。 ... [详细]
  • 本文介绍了 Go 语言中的高性能、可扩展、轻量级 Web 框架 Echo。Echo 框架简单易用,仅需几行代码即可启动一个高性能 HTTP 服务。 ... [详细]
  • 一、Tomcat安装后本身提供了一个server,端口配置默认是8080,对应目录为:..\Tomcat8.0\webapps二、Tomcat8.0配置多个端口,其实也就是给T ... [详细]
  • Spring Data JdbcTemplate 入门指南
    本文将介绍如何使用 Spring JdbcTemplate 进行数据库操作,包括查询和插入数据。我们将通过一个学生表的示例来演示具体步骤。 ... [详细]
  • 本文介绍了Spring 2.0引入的TaskExecutor接口及其多种实现,包括同步和异步执行任务的方式。文章详细解释了如何在Spring应用中配置和使用这些线程池实现,以提高应用的性能和可管理性。 ... [详细]
  • HTTP(HyperTextTransferProtocol)是超文本传输协议的缩写,它用于传送www方式的数据。HTTP协议采用了请求响应模型。客服端向服务器发送一 ... [详细]
  • 机器学习算法:SVM(支持向量机)
    SVM算法(SupportVectorMachine,支持向量机)的核心思想有2点:1、如果数据线性可分,那么基于最大间隔的方式来确定超平面,以确保全局最优, ... [详细]
  • 本文详细介绍了如何在 Linux 系统上安装 JDK 1.8、MySQL 和 Redis,并提供了相应的环境配置和验证步骤。 ... [详细]
  • 网站访问全流程解析
    本文详细介绍了从用户在浏览器中输入一个域名(如www.yy.com)到页面完全展示的整个过程,包括DNS解析、TCP连接、请求响应等多个步骤。 ... [详细]
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社区 版权所有