Skip to content

Instantly share code, notes, and snippets.

@vitiral
Created April 25, 2015 17:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitiral/b30e0860497f19bd6596 to your computer and use it in GitHub Desktop.
Save vitiral/b30e0860497f19bd6596 to your computer and use it in GitHub Desktop.
asyncio stack overflow question
import sys
import time
import socket
import asyncio
addr = ('127.0.0.1', 1064)
@asyncio.coroutine
def send_close(loop, sock, addr, data):
'''use the event loop to send data on the socket to addr, then close the
socket
'''
sock.setblocking(False)
try:
yield from loop.sock_connect(sock, addr)
yield from loop.sock_sendall(sock, data)
finally: sock.close()
@asyncio.coroutine
def accept_recv(loop, sock, limit=2500):
'''Use the socket object to accept a new connection and receive data.
returns the data received.
socket must be set to nonblocking
'''
recv, addr = yield from loop.sock_accept(sock)
try:
recv.setblocking(False)
data = yield from loop.sock_recv(recv, limit)
return data
finally: recv.close()
@asyncio.coroutine
def sending(addr, dataiter):
loop = asyncio.get_event_loop()
for d in dataiter:
print("Sending:", d)
sock = socket.socket()
yield from send_close(loop, sock, addr, str(d).encode())
@asyncio.coroutine
def receiving(addr):
loop = asyncio.get_event_loop()
sock = socket.socket()
try:
sock.setblocking(False)
sock.bind(addr)
sock.listen(5)
while True:
data = yield from accept_recv(loop, sock)
print("Recevied:", data)
finally: sock.close()
def main():
loop = asyncio.get_event_loop()
# add these items to the event loop
recv = asyncio.async(receiving(addr), loop=loop)
send = asyncio.async(sending(addr, range(10)), loop=loop)
loop.run_until_complete(send) # this prints until "8"
# run the loop once more, see question above
loop.stop()
loop.run_forever()
loop.stop()
loop.run_forever()
print("after forever?")
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment