I am simply trying to understand the context of
with open ('filename.png', 'rb') as f1
as I send sockets.
I can successfully copy / clone an internal file with ‘rb’ as f1, ‘wb’ as f2, but sending that over the socket protocol is driving me bonkers.
import socket import time import sys import os # lan scope HOST = "188.8.131.52" PORT = 8050 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((HOST, PORT)) sock.listen(1) # how many conenctions can it receive # listen for connecting client and sync / socket when reached out to conn,addr = sock.accept() print("Connected by ", str(addr)) i = True # send data until i = False then drop socket while i: # listen for what client tells you to do raw_data = conn.recv(1024) data = repr(raw_data)[2:-1] print(data) # if 'o' is pressed on client, send the file if (data == 'o') # below should copy the file using sock.send and client has sock.recv with open ('test.png','rb') as f1: sock.send(f1.read(1024)) sock.close() # if 'q' is pressed on client, quit if (data =='q'): i = False conn.close()
import socket import time HOST = "184.108.40.206" PORT = 8050 # Create socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # attempt to connect to host sock.connect((HOST,PORT)) connected = True while connected: message = input("Your Message: ") sock.send(bytes(message,'UTF-8')) if (message == 'o'): with open ('test1.png','wb') as remote: rec = sock.recv(1024) remote.write(rec) if (message == 'q'): connected = False sock.close()
I server side crashes with errno 32
Traceback (most recent call last): File "sendfile.py", line 36, in <module> sock.send(f1.read(1024)) socket.error: [Errno 32] Broken pipe
My first thought was “I am reading past the end of the file” but during each write, the client side test1.png filesize is still 0 meaning no data was ever received to be written to.
The python3 official documentation page is very difficult to read and the examples only use text/strings(which I already have working fine) and not binary files. The EXTENSIVE searching only has 2.7 examples without “with open” python 3.1 examples.
Thank you. I have spent probably about 20 hours trying to figure this out.