简体   繁体   English

python http服务器2路通讯

[英]python http server 2-way communication

I kind of a new with python and server programming and i'm trying to write a 2-way communication between server and multiple clients. 我对python和服务器编程有点陌生,我正在尝试在服务器和多个客户端之间编写2向通信。

I'm using pyhton json, requests library and baseHTTPServer 我正在使用pyhton json,请求库和baseHTTPServer

so far this is my code: Client: 到目前为止,这是我的代码:客户:

import requests
import json

if __name__ == '__main__':

    x = SomeClass()
    payload = x.toJson()
    print(j)

    headers = {
        'Content-Type': 'application/json',
    }
    params = {
        'access_token': "params",
    }
    url = 'http://127.0.0.1:8000'
    response = requests.post(url, headers=headers, params=params,
                             data=payload)

Server: 服务器:

from http.server import HTTPServer, BaseHTTPRequestHandler
import  json


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        # First, send a 200 OK response.
        self.send_response(200)

        # Then send headers.
        self.send_header('Content-type', 'text/plain; charset=utf-8')
        self.end_headers()

        length = int(self.headers.get('Content-length', 0))
        data = json.loads(self.rfile.read(length).decode())


if __name__ == '__main__':
    server_address = ('', 8000)  # Serve on all addresses, port 8000.
    httpd = HTTPServer(server_address, HelloHandler)
    httpd.serve_forever()

I have 2 questions: 我有两个问题:

  1. The data which I'm receiving at the server is ok but how do I send data back to the client? 我在服务器上接收的数据可以,但是如何将数据发送回客户端? I suppose I can do from the client something like busy wait every few seconds and send POST again and again but it feels wrong, after all the server is being triggered with do_POST without busy wait. 我想我可以从客户端执行一些操作,例如每隔几秒钟忙碌一次并一次又一次发送POST,但是在所有服务器都被do_POST触发而没有忙碌等待之后,感觉还是不对。

  2. If I have 10,000 clients connected to the server , how do I send data to a specific client? 如果我有10,000个客户端连接到服务器,如何将数据发送到特定客户端? I assume that if a connection been made so the socket is opened somwhere 我假设如果建立了连接,那么套接字将在某处打开

Below is some ASYNC base code to handle websocket requests. 以下是一些处理Websocket请求的ASYNC基本代码。 It is pretty straight forward. 这很简单。 Your JS will connect to the route localhost/ws/app and handle the data that should come in a JSON format. 您的JS将连接到路由localhost/ws/app并处理应采用JSON格式的数据。

from gevent import monkey, spawn as gspawn, joinall
monkey.patch_all()
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
from gevent import sleep as gsleep, Timeout
from geventwebsocket import WebSocketError
import bottle
from bottle import route, get, abort, template


@get('/app')
def userapp():
    tpl = 'templates/apps/user.tpl'
    urls = {'websockurl': 'http://localhost/ws/app'}
    return template(tpl, title='APP', urls=urls)

@route('/ws/app')
def handle_websocket():
    wsock = request.environ.get('wsgi.websocket')
    if not wsock:
        abort(400, 'Expected WebSocket request.')
     while 1:
        try:
            with Timeout(2, False) as timeout:
                message = wsock.receive()
            # DO SOMETHING WITH THE DATA HERE wsock.send() to send data back through the pipe
        except WebSocketError:
            break
        except Exception as exc:
            gsleep(2)


if __name__ == '__main__':
    botapp = bottle.app()
    WSGIServer(("0.0.0.0", 80)), botapp, 
    handler_class=WebSocketHandler).serve_forever()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM