I am trying to send an image from my local computer to a computer in the cloud using asyncio with TCP protocol. Sometimes I get the entire image being sent and sometimes only part of the image gets sent.
client code
import os
os.environ['PYTHONASYNCIODEBUG'] = '1'
import asyncio
import logging
logging.basicConfig(level=logging.ERROR)
async def tcp_echo_client(data, loop):
reader, writer = await asyncio.open_connection(<ip_addr>, <port>,
loop=loop)
print('Sending data of size: %r' % str(len(data)))
writer.write(data)
await writer.drain()
#print("Message: %r" %(data))
print(type(data))
print('Close the socket')
writer.write_eof()
writer.close()
with open('sendpic0.jpg','rb') as f:
data=f.read()
loop = asyncio.get_event_loop()
loop.run_until_complete(tcp_echo_client(data, loop))
loop.close()
server code:
import os
os.environ['PYTHONASYNCIODEBUG'] = '1'
import asyncio
import logging
logging.basicConfig(level=logging.ERROR)
async def handle_echo(reader, writer):
data = await reader.read()
addr = writer.get_extra_info('peername')
#print("Received %r from %r" % (message, addr))
print("Length of data recieved: %r" % (str(len(data))))
#with open('recvpic0.jpg','wb') as f:
# f.write(data)
print("Close the client socket")
writer.close()
#print("Message: %r" %(data))
print("Received data of length: %r" %(str(len(data))))
loop = asyncio.get_event_loop()
data=b''
coro = asyncio.start_server(handle_echo, '', <port_number>, loop=loop)
server = loop.run_until_complete(coro)
print("Received data of length: %r" %(str(len(data))))
# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
I didn't give the ip address and port number on purpose but it shouldn't matter.
Here is the output:
server output
Received data of length: '0'
Serving on ('0.0.0.0', 50001)
Length of data recieved: '249216'
Close the client socket
Received data of length: '249216'
Length of data recieved: '250624'
Close the client socket
Received data of length: '250624'
Length of data recieved: '256403'
Close the client socket
Received data of length: '256403'
client output
$ python client.py
Sending data of size: '256403'
Close the socket
$ python client.py
<class 'bytes'>
Close the socket
$ python client.py
Sending data of size: '256403'
<class 'bytes'>
Close the socket
I am using Python 3.6.
I don't know if I am supposed to have a checking mechanism or send data in chunks? I would assume all that would happen automatically under the read function.
I adjusted the code from this website: http://asyncio.readthedocs.io/en/latest/tcp_echo.html