我是编程新手,但我正在尝试通过套接字发送文件。在本例中是一个jpg,但其想法是让它发送任何大小的文件。我找不到足够的信息,我已经尝试谷歌和检查stackoverflow,但没有找到任何对我有帮助的东西,所以我决定在stackoverflow上询问。我正在使用PYTHON3
这个想法是一个服务器和一个客户端。客户端将向服务器发送一个文件。这是帮助的code....Thankful。
#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'
发布于 2018-06-23 06:42:31
您可能希望使用s.sendall(f.read())
而不是s.sendall(f.encode())
https://stackoverflow.com/questions/50995772
复制相似问题