[Tutor] Practicing with sockets

Bo Morris crushed26 at gmail.com
Fri Oct 31 20:42:20 CET 2014


Hey Danny, yes I have been having quite a bit of fun learning to work with
sockets. Thank you for your response. I have applied what you suggested
with the exception of the "logging." I read through the logging docs and
figured logging would be learning for another day. I have a hard time
enough staying focused on one task at time haha. I did however insert some
print statements into the code so I could keep track of where it was at,
but to keep my email short, I omitted them here.

After implementing what you suggested, the image fie that is saved on the
server is now 4 bytes, but I assume that is due to...

"Your client code will symmetrically read the first four bytes, use
struct.unpack() to find how how large the rest of the message is going to
be, and then do a loop until it reads the exact number of bytes"

and I have not quite got the correct loop to read all the bytes?

I also reread the docs at https://docs.python.org/2/howto/sockets.html and
decided to remove the "b" from "open('myfile.png', 'wb') open('myfile.png',
'rb')  seeing how binary could be different depending on the machine and I
have not yet learned how to deal with this. Would I be better off
converting the image to base64 prior to sending it to the server, then
decoding it on the server?

Here is my updated code...for brevity sake, I have omitted the "import"
statments...

Client:

f = open('/Users/Bo/Desktop/SIG.png', 'r')
strf = f.read()
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("ip,ip,ip,ip", 8999))
payload = client_socket.send(struct.pack("!I", len(strf)))
for data in payload:
    client_socket.sendall(strf)
f.close()
exit()

Server:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 8999
s.bind(('', port))
s.listen(5)
client_socket, address = s.accept()
data = client_socket.recv(4029)
f = open('img.png', 'w')
for item in data:
    f.write(item)
    f.flush()
f.close()
client_socket.close()

At least I am getting 4 bytes in oppose to 0 like I was getting before.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20141031/7f65b197/attachment.html>


More information about the Tutor mailing list