问题
I'm trying to write a simple client/server in Python using a TCP socket but I can't seem to figure out why the file is not transferring.
Client:
import socket
HOST = '' #server name goes in here
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST,PORT))
fileToSend = open('myUpload.txt', 'rb')
while True:
data = fileToSend.readline()
if data:
socket.send(data)
else:
break
fileToSend.close()
print 'end'
socket.close()
exit()
The print end is just to tell me that this client finished.
Server:
import socket
HOST = ''
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
file = open('myTransfer.txt', 'wb')
while True:
conn, addr = socket.accept()
data = conn.recv(1024)
print data
if data:
file.write(data)
else:
file.close()
break
socket.close()
exit()
The server was able to print out the correct data that was sent by the client but it was not able to save it into myTransfer.txt. The program seems to not be able to terminate even though I have a break statement in there. Any help would be very helpful. Thanks!
回答1:
You are calling accept
inside the while-loop. So you have only one recv
-call that receives data, so break
is never called.
Btw. you should use sendall
, that guarantees, that all data is sent.
Client:
import socket
HOST = '' #server name goes in here
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST,PORT))
with open('myUpload.txt', 'rb') as file_to_send:
for data in file_to_send:
socket.sendall(data)
print 'end'
socket.close()
Server:
import socket
HOST = ''
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
conn, addr = socket.accept()
with open('myTransfer.txt', 'wb') as file_to_write:
while True:
data = conn.recv(1024)
print data
if not data:
break
file_to_write.write(data)
socket.close()
来源:https://stackoverflow.com/questions/25273107/python-client-server-transfer-txt-not-writing-to-file