Получить практические навыки по работе с протоколом WebSocket
.
Пример WebSocket
echo сервера на Python
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import aiohttp
from aiohttp import web
async def hello(request):
return web.Response(text="Hello, world")
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == "close":
await ws.close()
else:
await ws.send_str(msg.data + "/answer")
elif msg.type == aiohttp.WSMsgType.ERROR:
print("ws connection closed with exception %s" % ws.exception())
print("websocket connection closed")
return ws
app = web.Application()
app.add_routes([web.get("/", hello)])
app.add_routes([web.get("/ws", websocket_handler)])
web.run_app(app) |
Пример AJAX
запроса:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | function get(url, callback, timeout=5 * 1000) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.timeout = timeout;
xhr.ontimeout = () => {
console.error("Timed out " + timeout + " " + url);
};
xhr.onerror = (e) => {
console.error(
"Error "
+ e.target.status
+ " occurred while receiving the document."
);
};
xhr.onreadystatechange = () => {
if (xhr.readyState === 4
&& (xhr.status === 200
|| (xhr.status === 0 && xhr.responseText))) {
try {
callback(JSON.parse(xhr.responseText));
} catch(e) {
callback(xhr.responseText);
}
} else {
}
};
xhr.send();
}; |
Написать WebSocket
сервер на языке Python
с использованием библиотеки
aiohttp
. Сервер должен уметь отдавать файлы по HTTP
запросу:
На этом же порту иметь возможность получить файлы по адресу
http://127.0.0.1:8080/ws
при помощи протокола WebSocket
.
См.также
Создать проект со следующей структурой:
myproject/
└── index.html
index.html
добавить javascript
код для получения содержимого
файлов с нашего сервер при помощи AJAX
и протокола WebSocket
.Добавить в index.html
форму для отправки запросов на получения содержимого
файлов.