WebSocket-Server server-side framework for the development of similar Flask for python3.X
1, the mounting module Pywss
pip install pywss
2, set up makeshift server
2.1 server code
Code Description
route
: Registration request pathexample_1(request, data)
:request
: Socket handle connected can transmit and receive data. Transmit datarequest.ws.send(data)
, receive datarequest.ws_recv(1024)
data
: Data sent by a client is stored in here
from pywss import Pyws, route @route('/test/example/1') def example_1(request, data): return data + ' - data from pywss' if __name__ == '__main__': ws = Pyws(__name__, address='127.0.0.1', port=8866) ws.serve_forever()
2.2 client code
Client code, it is recommended to run directly in the browser, eg: Chorme Open a new tab -> F12 -> console
Introduction Code
WebSocket(ws_url)
: Initiation Protocol upgraded to a WebSocket connection request, ws_url do wrong path slightly to the server inroute()
association with the registered pathws.onmessage
: When data transfer over, will perform this functionws.onclose
: When disconnecting, you will perform this functionws.onopen
: When the connection is established, it will perform this function
ws = new WebSocket("ws://127.0.0.1:8866/test/example/1"); ws.onmessage = function (ev) { console.log(JSON.parse(ev.data)); } ws.onclose = function (ev) { console.log('Connect Closed') } ws.onopen = function() { if (ws.readyState === WebSocket.OPEN) { ws.send('hello, pywss!') // you will get 'hello, pywss! - data from pywss' } }
Run shot:
Server:
Client:
github there are five examples of projects Address: https://github.com/CzaOrz/Pywss
If you feel good, it may give under me start ~ code to encourage small farmers QAQ