python http服务器2通通讯

时间:2018-10-24 18:15:34

标签: python httpclient httpserver

我是python和服务器编程的新手,我正在尝试在服务器和多个客户端之间编写双向通信。

我正在使用pyhton json,请求库和baseHTTPServer

到目前为止,这是我的代码: 客户:

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)

服务器:

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()

我有2个问题:

  1. 我在服务器上接收的数据可以,但是如何将数据发送回客户端?我想我可以从客户端执行一些操作,例如每隔几秒钟等待一次忙,然后一次又一次发送POST,但是在所有服务器都被do_POST触发却没有忙等待的情况下,感觉还是不对。

  2. 如果我有10,000个客户端连接到服务器,如何将数据发送到特定客户端?我假设如果建立了连接,那么socket在某处打开

1 个答案:

答案 0 :(得分:0)

下面是一些用于处理Websocket请求的ASYNC基本代码。这很简单。您的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()