search
HomeBackend DevelopmentPython TutorialIntroduction to WebSocket client programming under Tornado in Python

This article brings you an introduction to WebSocket client programming under Tornado in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Since WebSocket is one of the standards of HTML5, the Web client programming voice JavaScript of mainstream browsers already supports WebSocket client programming.

Client programming revolves around the WebSocket object. In JavaScript, you can initialize the WebSocket object through the following code:

var Socket=new WebSocket(url);

In the code, you only need to pass in the URL address of the server to the WebSocket constructor, such as http://mysite.com/point.

You can specify handler functions for the following events of this object to respond to them:

  • WebSocket.onopen: This event occurs on When the WebSocket connection is established.

  • WebSocket.onmessage: This event occurs when a message from the server is received.

  • WebSocket.onerror: This event occurs when there is any error during communication.

  • WebSocket.onclose: This event occurs when the server's link is closed.

In addition to these event handling functions, you can also perform active operations through two methods of the WebSocket object:

  • WebSocket.send(data): Send a message to the server.

  • WebSocket.close(): Actively close existing links.

The client WebSocket programming example program is as follows: index.html

nbsp;html>


    <meta>
    <title>WebSocket</title>


<a>运行WebSocket</a>
<p></p>


<script>
    var messageContainer=document.getElementById("messages");
    function WebSocketTest() {
        if("WebSocket" in window){
            messageContainer.innerHTML="浏览器支持WebSocket";
            var ws=new WebSocket("ws://localhost:8888/websocket?Id=12345");
            ws.onopen=function () {
                ws.send("onopen")
            };
            ws.onmessage=function (evt) {
                var received_msg=evt.data;
                messageContainer.innerHTML=messageContainer.innerHTML+"<br/>收到的信息:"+received_msg;
            }
            ws.onclose=function () {
                messageContainer.innerHTML=messageContainer.innerHTML+"<br/> 连接关闭了";
            }


        }else{
            messageContainer.innerHTML="浏览器不支持WebSocket"
        }
    }
</script>

The above code is analyzed as follows:

  • Client The main body of the page consists of two parts: a Run WebSocket link is used to allow users to start WebSocket; the other

    tag with id=message is used to display server-side messages.

  • Use the JavaScript statement if("WebSocket" in window) to determine whether the current browser supports the WebSocket object.

  • If the browser supports the WebSocket object, define the instance ws to connect to the WebSocket address of the server and pass in its own identifier parameter. Then define events through js syntax: onopen, onmessage, onclose processing functions. Except for the onopen event where the client sends a message to the server using the WebSocket.send() function, the other events only display the event results in the page

    tag.

The operation effect is as follows:

Introduction to WebSocket client programming under Tornado in Python

The above is the detailed content of Introduction to WebSocket client programming under Tornado in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

How does the memory footprint of a list compare to the memory footprint of an array in Python?How does the memory footprint of a list compare to the memory footprint of an array in Python?May 02, 2025 am 12:08 AM

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

How do you handle environment-specific configurations when deploying executable Python scripts?How do you handle environment-specific configurations when deploying executable Python scripts?May 02, 2025 am 12:07 AM

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.