python http服务器双向通信

2024-07-06 21:50:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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)

服务器:

^{pr2}$

我有两个问题:

  1. 我在服务器上接收到的数据是正常的,但是如何将数据发送回客户端?我想我可以在客户机上做一些事情,比如每隔几秒,然后一次又一次地发送POST,但是感觉不对,毕竟服务器是用dounupost而不是busy wait来触发的。

  2. 如果我有10000个客户机连接到服务器,如何将数据发送到特定的客户机?我假设如果建立了一个连接,那么套接字将在某处打开


Tags: 数据import服务器jsonurlpyhton客户机编程
1条回答
网友
1楼 · 发布于 2024-07-06 21:50:33

下面是一些处理websocket请求的异步基本代码。这很直接。您的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()

相关问题 更多 >