我是python的新手,这次我想在两个虚拟机之间发送一个文件,首先,虚拟机配置了NAT网络,两个虚拟机可以相互ping通。代码如下:
服务器端:
#server.py
import socket # Import socket module
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
# s.bind((host, port)) # Bind to the port
s.bind(('', port))
s.listen(5) # Now wait for client connection.
print 'Server listening....'
while True:
conn, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
data = conn.recv(1024)
print('Server received', repr(data))
filename='runbonesi.py'
f = open(filename,'rb')
l = f.read(1024)
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
conn.shutdown(socket.SHUT_WR)
print conn.recv(1024)
conn.close()
客户方:
#client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
#host = socket.gethostname() # Get local machine name
host = '10.0.2.15'
port = 60000 # Reserve a port for your service.
s.connect((host, port))
with open('received_file', '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 get the file')
s.close()
print('connection closed')
结果可以在以下图片中看到:
服务器端: result on server
客户方: result on client
问题是,客户端没有收到.py格式的文件,它只收到txt文件。请帮我解决这个问题。
谢谢。
答案 0 :(得分:0)
在客户端脚本中s.connect((host, port))
之后,您必须使用' hello'来编写s.send(...)
。你也忘了写文件扩展名' .py'在with open(...)
中(仅当您要将文件保存为Python脚本时!)。在关闭客户端连接之前,还必须添加s.send(...)
。