'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.
I'm using pyhton json, requests library and 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:
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.
If I have 10,000 clients connected to the server , how do I send data to a specific client? I assume that if a connection been made so the socket is opened somwhere
Solution 1:[1]
Below is some ASYNC base code to handle websocket requests. 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.
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eatmeimadanish |
