Skip to content

Instantly share code, notes, and snippets.

View ankitml's full-sized avatar
🎯
Focusing

Ankit ankitml

🎯
Focusing
View GitHub Profile
@ankitml
ankitml / async_http_benchmark.py
Last active August 28, 2018 18:43 — forked from nhumrich/async_http_benchmark.py
async vs threading http benchmark
from timeit import timeit
import asyncio
import requests
from threading import Thread
import aiohttp
client = aiohttp.ClientSession()
import asyncio
import websockets
from websockets.exceptions import ConnectionClosed
from time import sleep
async def connect():
while True:
try:
async with websockets.connect('ws://localhost:9999') as websocket:
backcall==0.1.0
decorator==4.3.0
hiredis==0.2.0
httptools==0.0.11
ipdb==0.11
ipython==6.5.0
ipython-genutils==0.2.0
jedi==0.12.1
parso==0.3.1
pexpect==4.6.0
@ankitml
ankitml / ws1.py
Last active February 6, 2019 20:02
Websockets Tutorial 1
import asyncio
import websockets
async def ws_handler(websocket, path):
async for message in websocket:
print(message)
if message == 'ping':
await websocket.send('pong')
@ankitml
ankitml / ws2.py
Created February 6, 2019 21:17
Websockets Tutorial 2 - Heart Beat
import asyncio
import websockets
async def heartbeat(websocket):
while True:
await asyncio.sleep(1)
await websocket.send('💚')
async def ws_handler(websocket, path):
@ankitml
ankitml / ws3.py
Created February 6, 2019 21:21
Websockets Tutorial 3 - Two simultaneous heart beats
async def beat1(websocket):
    while True:
           await asyncio.sleep(1)
           await websocket.send('💚')
async def beat2(websocket):
    while True:
           await asyncio.sleep(2)
           await websocket.send('💓')
async def beat1(websocket):
while True:
await asyncio.sleep(1)
await websocket.send('💚')
async def beat2(websocket):
while True:
await asyncio.sleep(2)
await websocket.send('💓')
@ankitml
ankitml / ws5.py
Created February 6, 2019 22:13
Websocet tutorial 5: Redis relay
from aioredis.pubsub import Receiver
REDIS_URL = 'localhost'
REDIS_PORT = 6379
async def redis_relay(websocket):
    conn = aioredis.create_connection((REDIS_URL, REDIS_PORT))
    receiver = Receiver()
    connection.execute_pubsub('subscribe', receiver.channel(‘updates’))
while (await receiver.wait_message()):
@ankitml
ankitml / ipctcp_client.py
Created February 14, 2019 14:48
client for ipc communication through tcp port
import asyncio
async def client(message):
message = message + '\n' + message + '\n'
reader, writer = await asyncio.open_connection(
'127.0.0.1', 8888)
print(f'Send: {message!r}')
writer.write(message.encode())
while True:
@ankitml
ankitml / ipctcp_server.py
Created February 14, 2019 14:49
IPC through tcp in python (server)
import asyncio
import random
async def handle_echo(reader, writer):
while True:
data = await reader.readline()
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
message = f'pong{random.randint(0,10)}\n'