There is a simple web server server in python.

import socket import json dictionary = {'Hello':'World'} dictionary_json = json.dumps(hardware) def parse_request(request): try: parsed = request.split() method = parsed[0] url = parsed[1] return (method, url) except: pass def generate_headers(method, url): if not method == "GET": return ('HTTP/1.1 405 Method not allowed\n\n', 405) return ('HTTP/1.1 200 OK\n\n', 200) def generate_content(code, url): if code == 404: return '<h1>404</h1><p>Not found</p>' if code == 405: return '<h1>405</h1><p>Method not allowed</p>' return dictionary_json def generate_respose(request): method, url = parse_request(request) headers, code = generate_headers(method, url) body = generate_content(code, url) return (headers + body).encode() def run_server(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('localhost', 8080)) server_socket.listen() while True: client_socket, addr = server_socket.accept() request = client_socket.recv(1024) print(request) response = generate_respose(request.decode('utf-8')) print(response) client_socket.sendall(response) client_socket.close() 

If you open a browser and go to localhost: 8080, then the contents of dictionary_json will be displayed on the screen. I would like the contents of the dictionary displayed on request javascript. That is, a simple html page with a button that, if pressed, would display the contents of the dictionary.

The question is actually how can this be implemented in the simplest way? I understand you need to use ajax requests and so on, but then how to process them by the server?

    1 answer 1

    There is a simple web server server in python.

     import socket 

    A common mistake is not a "websocket".


    if you really want to use WS - read on.

    Attention, the recommended library, as well as the code I didn’t check, is the first link from Google ( https://pypi.org/project/websockets/ ).

    The following text is a free translation of the part of the "Getting started" article , namely the section "Browser-based example".

    Requirements

    Python ≥ 3.4 (better than Python ≥ 3.6).

    Installation

    install dependencies with the following command

     pip install websockets 

    Browser-based example

    This is an example of how to start the WebSocket server and connect to it from a browser.

    run this script from the console

     #!/usr/bin/env python # WS server that sends messages at random intervals import asyncio import datetime import random import websockets async def time(websocket, path): while True: now = datetime.datetime.utcnow().isoformat() + 'Z' await websocket.send(now) await asyncio.sleep(random.random() * 3) start_server = websockets.serve(time, '127.0.0.1', 5678) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() 

    then create an index.html file with the following content and open it in a browser (eg from lane: just try dragging the file into the browser)

     <!DOCTYPE html> <html> <head> <title>WebSocket demo</title> </head> <body> <script> var ws = new WebSocket("ws://127.0.0.1:5678/"), messages = document.createElement('ul'); ws.onmessage = function (event) { var messages = document.getElementsByTagName('ul')[0], message = document.createElement('li'), content = document.createTextNode(event.data); message.appendChild(content); messages.appendChild(message); }; document.body.appendChild(messages); </script> </body> </html> 
    • Well, thanks, this method works. Is it possible to establish an ssl connection between the server and the client? Just if instead of: var ws = new WebSocket ("ws: //127.0.0.1: 5678 /") Write: var ws = new WebSocket ("wss: //127.0.0.1: 5678 /") In the javascript console, an error occurs: index.html: 55 Web connection connection to 'wss: //127.0.0.1: 5678 /' failed: Error in connection establishment: net :: ERR_SSL_PROTOCOL_ERROR - Gevol pm
    • secure-example - qwabra 7:56 pm
    • Yeah, I saw, I will understand. The only problem I have encountered is that the server is shutting down. asyncio.get_event_loop (). stop () asyncio.get_event_loop (). close () does not complete anything. sys.exit () also does not help. I would like to somehow shut down the server and the script completely and correctly. I did not find this in the documentation. - Gevol
    • You are trying to call the close method on the helper library and not on the socket. Try 'start_server.close ()' for more information, see the documentation, on the left is a konopochka api - qwabra