我正在尝试构建一个通过Python3套接字传输文件的程序。 这是我的服务器代码:
# server.py
import socket # Import socket module
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(4) # Now wait for client connection.
print ('Server listening....')
while True:
conn, addr = s.accept() # Establish connection with client.
print ('Got connection from', addr)
filename='send.rtf'
print ('File Assigned')
f = open(filename,'rb')
print ('File Oppened')
l = f.read(1024)
print ('Reading')
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(1024)
print ('Reading')
f.close()
print('Done sending')
conn.close()
这是我的客户代码:
# client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 60000 # Reserve a port for your service.
s.connect((host, port))
with open('recieved', 'wb') as f:
print ('file opened')
while True:
print('receiving data...')
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully got the file')
s.close()
print('Connection closed')
我在Mac上运行服务器,在PC上运行客户端。如果我在Mac上同时运行它们,程序运行正常,但不能在单独的机器上运行。这是我在PC上运行程序时出现的错误:
Traceback (most recent call last):
File "C:\Users\gshin\Desktop\P2PFile\P2PFileClient2.py", line 9, in <module>
s.connect((host, port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
非常感谢任何帮助!