我是编码的新手,但是我想通过套接字发送文件。在这种情况下,jpg是一个想法,但其想法是使它发送任何大小的文件。我找不到关于此的足够信息,我一直在尝试使用google并检查stackoverflow,但找不到任何可以帮助我的东西,因此我决定在此处询问stackoverflow。我正在使用PYTHON3
#SERVER CODE
import socket
import os
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("socket created...")
except:
print("failed creating a socket.")
def srv_1(host, port):
s.bind((host, port))
s.listen(5)
print("...Server Listening on port:", port, host)
while True:
c, addr = s.accept()
print("ACCEPTED CONNECTION:-> ", addr)
recivedData = c.recv(1024).decode() #this is going to be the
bits of file
print("file size is :", recivedData)
inpa = input("ACCEPT THE FILE? Y/N : ")
if inpa == 'Y':
acceptingFile = c.recv(1024).decode()
while recivedData > 1024:
data = c.recv(1024).decode()
print("Reciving entire file:", recivedData)
f = open(data,+"jpg", "wb")
print("...Done saving...")
elif inpa == 'N':
s.close()
print("...SOCKET CLOSED...")
f = open(data,+"jpg", "wb")
if __name__ == '__main__':
srv_1('127.0.0.1', 5460)
import socket
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 5460
def myC_F():
try:
s.connect((host, port))
print("connected to socket")
except:
print("failed connecting to: ", host, port)
fPath = input("Enter file to send:> ")
fSize = os.path.getsize(fPath)
fSize = str(fSize)
s.send(fSize.encode())
print("...DONE SENDING SIZE :", fSize)
while True:
with open(fPath, "rb") as f:
s.sendall(f.encode())
myC_F()
$python3 my_vers_CLIENT.py
connected to socket
Enter file to send:> /home/pythonious/Desktop/171.jpg
...DONE SENDING SIZE : 41846
Traceback (most recent call last):
File "my_vers_CLIENT.py", line 30, in <module>
myC_F()
File "my_vers_CLIENT.py", line 24, in myC_F
s.sendall(f.encode())
AttributeError: '_io.BufferedReader' object has no attribute 'encode'
答案 0 :(得分:0)
您可能想使用s.sendall(f.read())
而不是s.sendall(f.encode())